Archive for August, 2009

Search & Replace Strings Considering the whole file (non line-based) using ‘sed’ command

August 15, 2009

This was really stupid of ‘sed’ command. I had a file which had 2 occurances of the same string in 2 different lines and i wanted only the first to be replace by some other string. Took me a while to figure out why the conventional sed command doesnt work. (Incase you are wondering its because sed is a line-based command. i.e. reads a line from input, apply the whole sed logic and the mentioned operations in it, print the output and repeat the whole process for the rest of the input lines).

so anyway what you have to do is pretty simple. either you have to format your input to remove the new line characters and feed that as the input and somehow reintroduce the newline character after sed was applied, or feed the whole input to sed in a non-line-based form. Anyway found this on the net.

So coming back to what I wanted to do,

$ cat myfile | sed ‘:a;N;$!ba;s/originalstring/replacestring/’

notice the bolded characters added in the sed command. They are the extra addition to the conventional sed command we use for seach and replace strings.