sed tutorial: sed replace

Sed replace, you can use the sed function: s, replace the text in the file.


➜  ~ sed 's/regexp/replacement/' file


The sed command replaces the text in the file is the most commonly used function.

In the following example, we use the sed command to replace “hello” in the file with “hi”.

➜  ~ sed 's/hello/hi/' test.log

sed replace

The above example means replacing the first “hello” in each line with “hi”. Equivalent to the following command:

➜  ~ sed 's/hello/hi/1' test.log

Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “hello” with “hi” in a line.

➜  ~ sed 's/hello/hi/2' test.log

sed replace second match

Of course, we can also replace all “hello” in the file with “hi”. We can use the replacement flag / g (global replacement) to specify the sed command to replace all occurrences of the string in the line.

➜  ~ sed 's/hello/hi/g' test.log

Add a Comment

Your email address will not be published. Required fields are marked *