As part of their work, system administrators and technicians come across many instances where they have to replace some specific text in scripts or files on server.

sed , which stands for stream editor is an excellent utility/language for string editing. Its very powerful and can be used to do many complex string replacements that might not be possible with other simpler utilities like ‘replace‘ command in linux, however sed has some steep learning curve as well which is worth the benefits it provide.

In this post I will mention the simple text replacement sed command.

The basic syntax for the command is below :

sed -i 's/stringtomatch/stringtoreplace/g' targetfile

This command will replace ‘stringtomatch’ with ‘stringtoreplace’ in this case. ┬áThe -i or –in-place argument do the inplace editing to the original file and if you mention an extension it will create a backup file before doing the change. It would look like below :

sed -i".bak" 's/stringtomatch/stringtoreplace/g' targetfile

In this case a backup files named targetfile.bak will be created , before the string replacement is done to the original files named ‘targetfile’ in this case.

If we do not use the -i argument then no changes are made to the original file, but you can redirect the output to a second file, that would take the below form :

sed 's/stringtomatch/stringtoreplace/g' targetfile > newfilewithchages.txt

In this case the original targetfile will not get modified, rather they will be replacement in the other file where output is redirected, ‘newfilewithchanges.txt’ in this case.

If you have to do more than one string replacement in one command then -e or –expression argument can be used and multiple string replacement arguments can be supplied to make changes to the same file.

The command can take multiple expression and multiple input files, for complete synax check help for sed command.

Tags: , , , ,

Leave a Reply