Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

sed is short for stream editor. It reads in a file (one line at a time), modifies the contents per your parameters, and then outputs. 

Basics

A more simple description, it allows you to modify the contents of a file without you actually having to open it.

Basics

Sample File

Our sample text file called hey.txt looks like this,

Code Block
Hey, diddle, diddle,
The cat and the fiddle,
The cow jumped over the moon;
The little dog laughed
To see such sport,
And the dish ran away with the spoon.

Make sure to keep this file in your /opt/nursery/ directory.

Create this file with the above contents and also create a pristine version. We'll keep on reseting the file by copying back from the pristine version for each sample.

Simple Replace

Here a simple example of replacing the word original cow with new in a file called notesreindeer in the file hey.txt.,

Code Block
languagebash
sed -i 's/originalcow/newreindeer/' noteshey.txt

The -i signifies inline editing and also will have sed .

If you would like sed to automatically create a backup file specify the suffix of the backup file by adding .suffix. For example to create the backup file with the extension .sedautobck,

Code Block
languagebash
sed -i.sedautobck 's/cow/reindeer/' hey.txt

Reserved Character

Here is an often used example of escaping a the / (slash) which is a reserved character within the single quote,

Code Block
languagebash
sed -i 's/originalopt\/pathnursery/newvar\/pathryhme/' noteshey.txt # need to escape '/' since we are using it as a separator

...

Code Block
languagebash
sed -i 's,original/path,new/path,' noteshey.txt # do not need to escape '/' since we are using ',' as a separator

Detect if No Match Found

sed will exit gracefully with a return code of 0 even if a match is found. The sed return code by default is based on running properly not if your data matches.

One of the problems I've run into, thinking I successfully modified my files even though I did not. Here, I've made a mistake of using the word coy instead of cow,

Code Block
languagebash
sed -i.sedautobck 's/coy/reindeer/' hey.txt
cmp -s hey.txt hey.txt.sedautobck && echo "sed did not work, your files are identical."
sed did not work, your files are identical.

With the mistake you get the extra third line, "sed did not work, your files are identical.".

And if we want to be more fancy to make the cmp line more generic,

Code Block
languagebash
sed -i.sedautobck 's/coy/reindeer/' hey.txt
cmp -s $_ $_.sedautobck && echo "sed did not work, your files are identical."

Insert Multiple Lines from File with Match

...

Code Block
languagebash
sed '/cdef/r muliple-lines.txt' noteshey.txt

..

References

Simple introduction - http://www.grymoire.com/Unix/Sed.html
Another introduction - http://lowfatlinux.com/linux-sed.html

...