Text processing is a skill we must master using linux/unix. The last two articles introduced how to delete empty lines in text files and delete lines in text files that contain specified strings.
This article mainly introduces how to use the sed command to replace multiple patterns at once.
Before giving a formal introduction, let’s review how to use the sed command for replace pattern.
The following is the text file used in this test, we will use it to demonstrate how to use the sed command for string replacement.
This is a linux sed command test file.
sed replace pattern.
sed replace multiple patterns.
In the following example, we will use the sed command to replace the “sed” string in the test file with “awk“.
➜ ~ sed 's/sed/awk/g' text.log
➜ ~ sed -e 's/sed/awk/g' text.log
All of the above uses sed single pattern replacement. Let’s take a look at how to use the sed command for multiple patterns replacement.
replace multiple patterns
In the following example, we will use the sed command to complete multi-patterns replacement at once, replacing “sed” with “awk” and “command” with “cmd” in the test.
➜ ~ sed -e 's/sed/awk/g' -e 's/command/cmd/g' text.log
➜ ~ sed 's/sed/awk/g;s/command/cmd/g' text.log
If you want to modify the contents of the file directly, you can use the sed -i option.
The multi-patterns replacement completed with the sed command described above can also be achieved through multiple sed command combinations and pipelines.
➜ ~ sed 's/awk/sed/g' text.log | sed 's/command/cmd/g'