Saturday, March 26, 2016

Search and replace | Linux command "sed"


SED, search and replaceNext to the commands grep and cut the sed command is what I often use. Using the sed command you can search and replace strings in files. I find this tool handy when it comes to configuration files.

You can create template files from configuration files where you would put a unique string on the configuration items and then use set to replace these values.
Lets take the following contents of the file fruit.txt for example.
apple green tree
banana yellow tree
strawberry red plant
Now you could replace the word apple with pear by executing the following command.
sed 's/apple/pear/g' fruit.txt
pear green tree
banana yellow tree
strawberry red plant
In the command parameter above you see the "s" which stands for search and the "g" for global or search the whole file.

I use this for configuration files which have for example the Listen configuration item. Then I would save the file locally and set the Listen parameter to be "addrport" then I use the above command for this.
sed 's/addrport/192.168.1.10:80/g' /etc/httpd.conf
...
Listen 192.168.1.10:80
...
The above command with its parameters outputs the result to the standard output (to the shell) so if you want to leave the source file intact you can write the output to another file as well. You can do this like this.
sed 's/addrport/192.168.1.10:80/g' /etc/httpd.conf > /tmp/httpd.conf
And if you want to modify the source file directly (can be dangerous though) you can add the -i parameter which means in file.
sed -i 's/addrport/192.168.1.10:80/g' /etc/httpd.conf
As with most Linux command line tools and commands sed has a great variety of parameters and options. I mostly use the sed command like in the examples but you can find the manual here

No comments:

Post a Comment

How to create a software RAID array in Linux | mdadm

In my previous post I explained on the most common used RAID levels and their write penalties. In this post I will show how you c...