Using sed to perform text replacement

sed stands for stream editor. It is a very essential tool for text processing, and a marvelous utility to play around with regular expressions. A well-known usage of the sed command is for text replacement. This recipe will cover most of the frequently-used sed techniques.

How to do it…

sed can be used to replace occurrences of a string with another string in a given text.

  1. It can be matched using regular expressions.
    $ sed 's/pattern/replace_string/' file


    $ cat file | sed 's/pattern/replace_string/'

    This command reads from stdin.


    If you use the vi editor, you will notice that the command to replace the text is very similar to the one discussed here.

  2. By default, sed only prints the substituted text. To save ...

Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.