Using sed to perform text replacement
sed stands for stream editor. It's most commonly used for text replacement. This recipe covers many common sed techniques.
How to do it...
The sed command can replace occurrences of a pattern with another string. The pattern can be a simple string or a regular expression:
$ sed 's/pattern/replace_string/' fileAlternatively, sed can read from stdin:
$ cat file | sed 's/pattern/replace_string/'Note
If you use the vi editor, you will notice that the command to replace the text is very similar to the one discussed here. By default, sed only prints the substituted text, allowing it to be used in a pipe.
$ cat /etc/passwd | cut -d : -f1,3 | sed 's/:/ - UID: /' root - UID: 0 bin - UID: 1 ...
- The
-Ioption will causesedto replace the original file with the modified data:
$ sed -i 's/text/replace/' file
- The previous example replaces the first occurrence of the pattern in each line. The
-gparameter will causesedto replace every occurrence...