Sed command

Unix Shell

We already discovered basic shell commands and we also used more powerful grep command but it’s time to discover less popular command: sed command.

Sed command replaces contents in a given file and then display changed version in a shell. You can also use base regular expressions and even save the previous version of contents in a backup file but let’s check this on examples.

Replace contents and show changed version – don’t change the original file

The base version of sed command requires two arguments: file name and string that contains the original string and its replacement:

sed `s/Mark/Tom/` names.txt

Above command will replace name Mark with Tom in the names.txt file and then show file contents in a shell – it would not change contents in the file, it just replaces things and displays changed version.

Replace contents, save the changed version and create a backup file

If you want to replace contents in an original file but also save previous contents in a backup file then you should usei option:

sed -i `.old` `s/Mark/Tom/` names.txt

Above command will replace names but also create file names.txt.old with previous contents. If you want to quickly restore previous contents you can use the following command:

mv names.txt.old names.txt

Replace contents, save the changed version without backup

You may want to change original file but without backup – in order to do this, just pass i option with blank value:

sed -i `` `s/Mark/Tom/` names.txt

Use regular expressions

If simple replacement is not enough then you can combine it with simple regular expressions. Let’s assume that you want to replace Mark and Simon names to Tom then you can use the following version instead of using sed twice with different names:

sed `s/Mark|Simon/Tom/` names.txt

Sed may not be as useful as grep in a daily development but it will become more useful for more complex shell commands organized into simple programs