Sed, Linux text editor

From The World according to Vissie
Jump to navigation Jump to search

http://www.linuxhowtos.org/System/sedoneliner.htm?ref=news.rdf

# delete leading whitespace (spaces, tabs) from front of each line
# aligns all text flush left
sed 's/^[ \t]*//' # see note on '\t' at end of file
# delete BOTH leading and trailing whitespace from each line
sed 's/^[ \t]*//;s/[ \t]*$//'
# substitute (find and replace) "foo" with "bar" on each line
sed 's/foo/bar/' # replaces only 1st instance in a line
sed 's/foo/bar/4' # replaces only 4th instance in a line
sed 's/foo/bar/g' # replaces ALL instances in a line
# substitute "foo" with "bar" ONLY for lines which contain "baz"
sed '/baz/s/foo/bar/g'
# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
sed '/baz/!s/foo/bar/g'

The sed regular expressions are essentially the same as the grep regular expressions. They are summarized below.

Character	Description
^	        Matches the beginning of the line
$	        Matches the end of the line
.	        Matches any single character
*	        Will match zero or more occurrences of the previous character
[ ]	        Matches all the characters inside the [ ]

Probably the best way to get your feet wet with regular expressions is to see a few examples. All of these examples will be accepted by sed as valid addresses to appear on the left side of a command. Here are a few: Regular expression Description

/./	        Will match any line that contains at least one character
/../	        Will match any line that contains at least two characters
/^#/	        Will match any line that begins with a '#'
/^$/	        Will match all blank lines
/}$/	        Will match any lines that ends with '}' (no spaces)
/} *$/	        Will match any line ending with '}' followed by zero or more spaces
/[abc]/	Will match any line that contains a lowercase 'a', 'b', or 'c'
/^[abc]/	Will match any line that begins with an 'a', 'b', or 'c'