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/' file
Alternatively, sed can read from stdin:
$ cat file | sed 's/pattern/replace_string/'
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 -I option will cause sed to 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 -g parameter will cause sed to replace every occurrence:
$ sed 's/pattern/replace_string/g' file
The /#g option will replace from the Nth occurrence onwards:
$ echo thisthisthisthis | sed 's/this/THIS/2g'
thisTHISTHISTHIS
$ echo thisthisthisthis | sed 's/this/THIS/3g'
thisthisTHISTHIS
$ echo thisthisthisthis | sed 's/this/THIS/4g'
thisthisthisTHIS
The sed command treats the character following s as the command delimiter. This allows us to change strings with a / character in them:
sed 's:text:replace:g'
sed 's|text|replace|g'
When the delimiter character appears inside the pattern, we have to escape it using the \ prefix, as follows:
sed 's|te\|xt|replace|g'
\| is a delimiter appearing in the pattern replaced with escape.