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

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.


Tags: , ,

2 Responses to “Search & Replace Strings Considering the whole file (non line-based) using ‘sed’ command”

  1. Says:

    thanks.. nice info

  2. Sakis Hrist Says:

    Hi. I have used this for a very long time now. So thanks for the sharing it.

    I happened to stumble upon an issue with this though: if your input consists of only one line, this approach will not work at all. So a quick fix was to add another check for the last line, like this: :a;$!N;$!ba;

    There might be a better way instead of doing the same check twice every time, but this was the quickest fix I could think of.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: