Basic Usage of Sed

28 Jan 2013

sed is __s__tream __ed__itor. It is a powerful command line utility you see often in bash scripts. In the ‘man’ page, it says “it is sed’s ability to filter text in a pipeline which particularly distinguishes it from other types of editors.”

Most important of all, it processes the input stream in ONE pass, which makes it very efficient. The basic (and most common) usage of sed is to substitue all occurrences of the regular expression into a new value. For example:

$ echo day | sed s/day/night
night

The basic syntax of sed s command is:

# Change "day" in the "old" file to "night" in the "new" file
$ sed s/day/night/ <old >new

To see the real power of sed with pipes:

# If you want to make two changes, you can pipe it together!
$ sed 's/BEGIN/begin/' <old | sed 's/END/end/' >new

# the command above created TWO processes instead of one 
# below is a better alternative which combines multiple 
# commands together without pipelining!
$ sed -e 's/BEGIN/begin/' -e 's/END/end/' <old >new

REFERENCE