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.

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

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

Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!