Site icon LinuxCommands.site

sed tutorial: sed replace

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

syntax

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

examples

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

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

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

Exit mobile version