Linux / Unix: Sed Substitute Multiple Patterns [ Find & Replace ]

The sed command is a powerful tool in Linux and Unix for text processing and manipulation. You can use the sed command to substitute multiple patterns, or to find and replace text within a file.

Here’s how you can use sed to substitute multiple patterns in a file:

  1. Substitute multiple patterns in place To substitute multiple patterns in place, you can use the following syntax:
    $ sed -i 's/pattern1/replace1/g; s/pattern2/replace2/g; ...' filename

    The -i option is used to edit the file in place, and the g flag at the end of each substitution expression is used to replace all occurrences of the pattern in each line.

  2. Substitute multiple patterns and write output to a new file If you want to substitute multiple patterns, but not edit the original file, you can use the following syntax to write the output to a new file:
    $ sed 's/pattern1/replace1/g; s/pattern2/replace2/g; ...' filename > newfile

Here’s an example to illustrate the use of sed to substitute multiple patterns in a file:

$ cat test.txt
This is a test file
This is line two

$
sed -i 's/This/That/g; s/test/sample/g' test.txt

$
cat test.txt
That is a sample file
That is line two

In this example, the sed command is used to substitute the patterns “This” with “That”, and “test” with “sample”, in the file test.txt. The output of the command is saved back to the same file using the -i option.

Leave a Comment