SED is a stream editor for filtering and transforming text.  I use SED often to manipulate text files on the fly.  Most of the same manipulation can be done with Perl, Awk and ???  Everyone has their own preference.  SED is what I know the best, so it’s what I use.

When using SED you have options, the two I use most are to show the potential outcome of the edit and the other is to actually edit the file.

# sed [just show the changes, but don’t make them permanent]
# sed -i  [edit in place]

Note: The following examples may or may not show the -i attribute.  Remember, sometimes we maybe want to look at the changes but not make them permanent.

These are just a few examples. There is more to come.

Add

Add something to the front of each line
# sed ‘s/^/something/’ file1

Add something to the end of each line
# sed ‘s/$/something /’ file1

Find the line containing text icmp-host-prohibited in file iptables and put a # in front
# sed -i ‘/icmp-host-prohibited/ s/^/#/’ /etc/sysconfig/iptables ;

Find the line containing text COMMANDS and append “,/sbin/chkconfig” to it.
# sed -i ‘/Cmnd_Alias COMMANDS/ s/$/,\/sbin\/chkconfig/’ /etc/sudoers

Find text in a file and add a new line after it
# sed -i ‘/HISTSIZE=1000/ a\TMOUT=10000’ /etc/profile

Replace

Replace all strings “can” by “should”
# sed ‘s/can/should/g’ file1

Replace first instance of “can” with “should” (works in script)
# sed -i -e ‘1s/should/can/;t’ -e ‘1,/should/s//can/’ csfile ;

Replace > with \> in an html file
# sed ‘s/>/\>/g’ file.html    

Remove

Remove all blank lines
# sed ‘/^$/d’ file1

Remove to the beginning of a line to the first “,”
# sed -i ‘s/^.*,//g’ file1

Remove: Find string test in file1 and remove line with first instance
# sed ‘/test/d’ file1

Prepend

More to come

Append

More to come