sed is a non-interactive text editor that comes with UNIX since Version 7 AT&T UNIX. It's main purpose is to be used in scripts.
sed works as a filter, which makes it particularly useful for scripts. sed works line oriented. The most simple commands are a pattern and an action. If no pattern is given, the action is applied to all lines, otherwise it is applied only to lines matching the pattern.
A sample application of sed would be to delete the first 10 lines of stdin and echo the rest to stdout:
sed -e '1,10d'
If we wanted to print only the first ten lines, we would have deleted all the lines starting with 11:
sed -e '11,$d'
Another way to get only the first 10 lines is to use the -n option:
sed -n -e '1,10p'
Commands in sed programs are separated by new lines. So if we wanted to delete the lines 1 to 4 and 6 to 9, we could use:
sed -e '1,4d
6,9d'
sed -e '1,4d' -e '6,9d'
Often, we don't know the numbers of the lines we want to delete. A good example is a log file. Log files tend to grow until they become too large to handle. Let's assume that you have a large log file called log which contains thousands of lines. Now you want to delete all the lines that contain the word ``debug``:
sed -e '/debug/d' log
We are still working with the large log file. Now we not only want to delete lines with the word debug, but we only want lines that contain ``foo``. The traditional way to handle this would be:
grep 'foo' log | grep -v debug
sed -n -e '/debug/d' -e '/foo/p'
Now that your programs are getting a little more advanced, you might want to put them in script files instead of using the command line. To tell sed(1) about your program file, you use the -f option:
sed -f program.sed
You can insert text with the ``a`` and ``i`` actions. The syntax is:
10i
string to be inserted
You can replace the current line with the ``c`` action. The syntax is like ``i`` and ``a``:
10c
new contents for line 10
The ``l`` action is very useful when editing files with nonprintable characters. It prints the current line visually unambiguously. For example, long lines are broken, but the lines end with a to show that they were broken. Normal backslashes in the text are escaped, too, tabs are replaced with and nonprintable characters are printed as escaped three-digit octal numbers. This example is quite useful as shell alias:
sed -n -e 'l'
The ``q`` action branches to the end of the script and ends the script processing after this line. So, yet another way of printing the first 10 lines would have been:
sed -e '10q'
The ``s/pattern/replacement/[flags]`` action is the most often used sed(1) action. In fact, most sed programs consist only of substitute commands, since this is so immensely useful. The regular expression pattern is substituted by the replacement string (which can contain several special symbols). The most basic substitution would be
sed -e 's/foo/bar/'
From http://www.ceri.memphis.edu/computer/docs/unix/sed.htm
A handy set of one-liners for sed