Tuesday 26 May 2009

Editing multiple files with sed

Sed is a very useful stream editor for Linux.
A stream editor is used to perform basic text transformations
on an input stream, such as replacing a text string with another
text string. While in some ways similar to an editor which permits
scripted edits(such as ed), sed works by making only one
pass over the input(s), and is consequently more efficient. But it
is sed's ability to filter text in a pipeline which particularly
distinguishes it from other types of editors.

For example, if you want to replace the text "a rainy day" with
the text "a bright and starry night" in a text file containing
the sentence "It was a rainy day outside.", you can do it from the prompt
like this:

sed -i "s/a rainy day/a bright and starry night/g" textfile.txt

This command will have changed the text in your file to "It was a bright
and starry night outside.
". The nice
thing is that you can use it to edit
the same string in multiple
files at once. You can also use other
separators than "/". The
above command would have been equally valid
if it was written as:


sed -i "s|a rainy day|a bright and starry night|g" textfile.txt

All in all, sed is quite a powerful way to manipulate strings.

0 comments: