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

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

To substitute multiple patterns using the sed command, you can use multiple s/pattern/replacement/ commands separated by a semicolon.

For example, to replace both the words hello and world with greetings, you can use the following command:

refer ‮t‬o:lautturi.com
sed 's/hello/greetings/;s/world/greetings/' input.txt > output.txt

This will read the file input.txt, replace all occurrences of the word hello with greetings and all occurrences of the word world with greetings, and save the resulting output to output.txt.

You can also use the -i option to edit the file in place, rather than creating a new output file. For example:

sed -i 's/hello/greetings/;s/world/greetings/' input.txt

This will replace all occurrences of the words hello and world with greetings in the file input.txt.

You can use regular expressions to match patterns in the sed command. For example, to replace all words that start with the letter a with the word apple, you can use the following command:

sed 's/a[a-zA-Z]*/apple/g' input.txt > output.txt

This will read the file input.txt, replace all words that start with the letter a with the word apple, and save the resulting output to output.txt. The g at the end of the substitution pattern tells sed to perform the replacement globally, so all occurrences of the pattern will be replaced.

For more information about using the sed command, you can refer to the sed manual page or use the --help option. For example:

man sed
sed --help
Created Time:2017-10-29 22:08:59  Author:lautturi