Utility Notes - Using sed Cntd
sed source: Sed will read from a file or 'Standard In' and therefore may be used in piped sequences.
The following two lines are functionally equivalent:
cat file |sed 'search expression' > file.mod
sed 'search expression' file > file.mod
sed with substitution: :sed's major use for most of us is in changing the contents of files using the substitution feature.
Subsitution uses the following expression:
# substitution syntax
sed '[position]s/find/change/flag' file > file.mod
# where
# [position] - optional - normally called address in most documentation
# s - indicates substitution command
# find - the expression to be changed
# change - the expression to subsituted
# flag - controls the actions and may be
# g = repeat on same line
# N = Nth occurence only on line
# p = output line only if find was found!
# (needs -n option to suppress other lines)
# w ofile = append line to ofile only if find was found
# if no flag given changes only the first occurrence of
# find on every line is substituted
# examples
# change every occurrence of abc on every line to def
sed 's/abc/def/g' file > file.mod
# change only 2nd occurrence of abc on every line to def
sed 's/abc/def/2' file > file.mod
# creates file changed consisting of only lines in which
# abc was changed to def
sed 's/abc/def/w changed' file
# functionally identical to above
sed -n 's/abc/def/p' file > changed
Line deletion:sed provides for simple line deletion.
The following examples illustrate the syntax and a trivial example:
# line delete syntax
sed '/find/d' file > file.mod
# where
# find - find regular expression
# d - delete command
# delete every comment line (starting with #) in file
sed '/^#/d' file > file.mod
Delete vs Replace with null: If you use the delete feature of sed it deletes the entire line on which 'search expression' appears, which may not be the desired outcome. If all you want to do it delete the 'search expression' from the line then use replace with null.
The following examples illustrate the difference:
# delete (substitute with null) every occurrence of abc in file
sed 's/abc//g' file > file.mod
# delete every line with abc in file
sed '/abc/d' file > file.mod
Escaping: You need to escape certain characters when using as literals using the standard \ technique. This removes the width attribute from html pages that many web editors, such as frontpage, annoyingly place on every line. The " are used as literals in the expression and are escaped by using \:
# delete every occurrence of width="x" in file
# where x may be pure numeric or a percentage
sed 's/width=\"[0-9.%]*\"//g' file.html > file.mod