Home » Featured, Linux

Find and Replace with SED

27 March 2011 No Comment

Find and Replace with SEDThe power of search and replace is prevalent all over Linux. Whether you are using a text editor or on the command line, regular expressions come in handy.

When you are using a text editor such as vi, you are probably familiar with the search and replace feature. From the command line, the find and replace feature is also available if you use sed.

SED, a Unix utility, is a stream editor that can parse text that you provide and transform it into whatever you like. Sed has been around since the 1970s and it is a successor to the popular grep command. You would use sed if you have a file that you want to search the contents for a particular string and you want to replace it with something else.

Suppose you stayed at a restaurant and you took notes while you were there. You wanted to keep the memories by writing some notes in a file. At that time, you didn’t know the name of the fish that you ate so you just called it fish. When you got home, you did some research and found out that the fish was called Tilapia. You can use vi to edit all occurrences of this word or you can do it from the command line.

If you use sed, it can replace the word faster than you can type the command. Run the command below:

$ sed -i ‘s/fish/Tilapia/g’ /home/kevin/restaurants/dinner.txt

The -i option means that you want to edit the file dinner.txt in place. The s stands for substitute and the g stands for global. In this case, it means sed will search for all occurrences of the word fish and replace it with the word Tilapia.

If you don’t want to do an in-place search and replace, you can use the -e option instead. This way you can specify another file with the changes and preserve the original file.

$ sed -e ‘s/fish/Tilapia/g’ /home/kevin/restaurants/dinner.txt > /home/kevin/restaurants/updated_dinner.txt

The -e option allows you to redirect the changes you make from a file to another file. In this case, you are replacing the word fish with Tilapia and saving it in a new file called updated_dinner.txt.

The commands above only works if you have one file you want to edit. If you have multiple files you want to edit at the same time, you can do so by combining the find command with sed.

$ find /home/kevin/restaurants -type f -exec sed -i ‘s/fish/Tilapia/g’ {} \;

These two commands will search through the restaurants folder, find all files, and search and replace the word fish with Tilapia.


Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.