Friday, January 28, 2005

SED - Replace patterns in a file using sed

One of the best tools for editing a stream of characters is sed. In fact sed stands for stream editor. One of my favorite commands in sed is the substitute command. The command syntax is as follows:
$ sed 's/orig/new/' source > dest

The command uses regular expressions and hence "orig" is a regular expression. The command substitutes all occurences of the original pattern with "new".

As can be seen the output has to be redirected to another file. This is because sed sends the output to stdout. To substitute things in the same file, use the following format:
$ sed 's/orig/new/' source > dest && /bin/mv dest source && /bin/rm dest

Hope this helps.
Rgds,
Karthick S.

3 comments:

Anonymous said...

Thanks for ur ready-made commands.

well, the syntax has to be sed 's/orig/new/' source > dest

"/" after "new" is missing. If we give the command as given by you then it responds as "command garbled"

Karthick S said...

Thanks.

That was a genuine error.

Rgds,
Karthick

Anonymous said...

Thank you, this was exactly what I was looking for! Much better and quicker than those lengthy tutorials and introductions.