...
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 cow with reindeer in the file hey.txt,
Code Block | ||
---|---|---|
| ||
sed -i 's/cow/reindeer/' noteshey.txt |
The -i signifies inline editing and also will have sed automatically creates a backup file. If you want to specify the suffix of the backup file you may add .suffix. For example to create the backup file with the extension .bak,
Code Block | ||
---|---|---|
| ||
sed -i.bak 's/cow/reindeer/' noteshey.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 | ||
---|---|---|
| ||
sed -i 's/opt\/nursery/var\/ryhme/' noteshey.txt # need to escape '/' since we are using it as a separator |
...
Code Block | ||
---|---|---|
| ||
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.
To determine if there was a match to your file,
Code Block | ||
---|---|---|
| ||
Insert Multiple Lines from File with Match
...
Code Block | ||
---|---|---|
| ||
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
...