Click to See Complete Forum and Search --> : substituting and adding text to a file


gamblor01
02-14-2006, 01:16 PM
Hey, I think I can use sed for this, but I haven't figured out exactly how yet. I know how to substitue with sed, it's just sed 's/pattern_to_match/pattern_to_sub/g' to do it globally in a file.

The problem is, what if I want to find all occurences of a function call in a file, and add another function call after it? For example, if I have the following lines in a file....


http_recv("asdf");
more lines....

http_recv("blah");
more

http_recv("foo");


and suppose I want to call a function bar(); after every instance of the call to http_recv so it now looks like this:


http_recv("asdf");
bar();
more lines....

http_recv("blah");
bar();
more

http_recv("foo");
bar();



I can't just do sed 's/http_recv$/bar();/g' because that will overwrite the line starting with http_recv...and I want to keep it there and merely append essentially a \nbar(); to the end of it. Is there a way sed can do that? I was thinking it would be cool if maybe the http_recv$ could become a parameter or something of the -s option, so if I could do like sed 's/http_recv$/$0\nbar\(\);/g' or something that would be really cool where the $0 parameter refers to the pattern that http_recv$ had just matched...but I don't think it's that simple.

I read the man page and it looks like there's an N option to append to the next line, but I can't seem to get the command to work properly on some files I've tested. Anyone know how to do this? Thanks!

gamblor01
02-14-2006, 05:31 PM
Nevermind I found out how to do it with awk. Just in case you're wondering...



awk '{print $0}/http_recv/{print "bar();"}' file


:)