Friday, January 28, 2005

Basics of SED

Some points about sed that we need to know on day 1 of learning sed:
1) Sed is a stream editor and hence takes input from a file or group of files.
2) By default, the output of sed is displayed in stdout. If we want the output to be stored in a file, then we can redirect it to some temporary file using >.
3) Sed scripts can be written and sed commands can also be used in shell scripts.
4) Since sed, like most other Unix utilities, takes input from stdin and gives output to stdout, piping is possible.

I will follow this up with a list of tips on sed usage.

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