Home > posts > Seduced by sed

Seduced by sed

July 25th, 2009 subogero

So I started searching the internet about the usage of sed, the ultimate stream editor. I found the number one site about the Awful Truth. If you have any question about sed, you’ll find the answer here. My favourites so far:

Simple replacement of “Windows” to “Linux”, sorry “foo” to “bar” with the magic s (substitution), go for all occurrences this time with flag g (global).

sed -e 's/foo/bar/g'

Use any other delimiter instead of slash, in this case the comma, if slash is used in any pattern.
Keep a part of a matched string defined by the brakets \( \) and using \1.
Let’s convert “c:” to “/cygdrive/c”.

sed -e 's, \([A-Za-z]\):, /cygdrive/\1,g'

You will also notice the presence of the dreaded regular expression above. I also learned that sed is a so-called filter. In streams the standard input, so sed takes the text you type, and writes the result to the terminal window.

And now comes the best part, at least for a rookie like me, the redirection wizardry. You can redirect sed’s input or output to any other file, or even any other program’s standard input or output.

For instance let’s copy the contents of foo.txt to bar.txt, but will all occurrences of “foo” replaced with “bar”.

sed -e 's/foo/bar/g' <foo.txt >bar.txt

Same operation but replace in the same file, foo.txt.

sed -e 's/foo/bar/g' -i foo.txt

And using the pipe and the command-quote you can do the same between environment variables, as well. The pipe “|” connects the output of the program on its left to the input of the one on its right. And the command quote ` ` redirects the final output to a variable.

BAR=`echo $FOO | sed -e 's/foo/bar/g'`

I think it’s obvious by now that I’m infected. I use the words “foo” and “bar”.

Categories: posts Tags:
Comments are closed.