Unix shell

Sed command – Unix shell

Sed command – Unix shell January 5, 2018Leave a comment
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 original file

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

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

Above command will replace name Mark with Tom in 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 changed version and create backup file

If you want replace contents in an original file but also save previous contents in a backup file then you should use i 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 following command:

mv names.txt.old names.txt

Replace contents, save 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

Image source: pexels.com

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

Leave a Reply

Your email address will not be published. Required fields are marked *