The sed command is one of those commands I have never put enough attention in Linux. A mistake! The sed command (Stream Editor) is a very powerful one to know. It is used to find and replace text patterns.

Sed command standard sysntax

sed 's/pattern/replacement/flags' somefile

To replace all instances of Paco with Timo in a file.txt:

sed 's/Paco/Timo/g' file.txt
s/ - Substitute command.
g - Replaces all occurrences on a line, not just the first.
i - Ignore case.

sed is a Stream Editor. It reads text from an input (file or pipe) and sends the result to standard-output(your terminal screen). This is to safely prevent errors when making changes to files.

Write changes to a file using sed

You will need to use the -i flag. For example:

sed -i 's/Mary/Jenny/g' names.txt

The above will write changes/edit the file ‘in-place’ instead of displaying it on the screen only.

To prevent issues use the safety tips below:

sed -i.bak 's/Mary/Jenny/g' names.txt

The above will create a backup file named: names.txt.bak that you can use in case you made a mistake.

sed 's/Mary/Jenny/g' names.txt > new-names.txt

The above sed command will redirect the output of the command into a new file named new-names.txt. Very cool! Remember, DO NOT use the same file name.

After learning more about the this useful command I feel more comfortable and decided to brew a nice cup of Catimor coffee at home.

Leave a comment

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