Linux uses the sed command to replace the string tutorial

  • 2020-12-26 06:49:57
  • OfStack

To replace the string, we need to use the following format.


$ sed s/ Replace the target string / The replaced string /  The file name 

Below we replace the string "sample.txt" with "appleorangemelon".


$ sed s/orange/ORANGE/ sample.txt

The execution result is


appleORANGEmelon

Replace and output the string.

Also, as shown below, you can get the same result by connecting the sed command with "|" after the cat command.


$ cat sample.txt | sed s/apple/APPLE/

Note that the sed command only replaces the string and outputs it, but does not override the contents of the actual file

If you want to save the replacement in text, use the "redirect" > ".

Options used by the sed command

命令选项 说明
-e 替换为指定的脚本
-f 文件 添加指定文件中描述的脚本文件的内容
-r 使用扩展正则表达式

Use of the sed command

Replace all rows

In the format described earlier, only the first matching string is replaced, even if there is a string matching more than one replacement object string in a single line.

Therefore, to replace all matching strings, do the following:


$ sed -e s/apple/APPLE/g sample.txt

The execution result is


APPLEorangemelonAPPLE

Replace the beginning and end of a line


$ sed -e "s/^apple/APPLE/" sample.txt
$ sed -e "s/apple\$/APPLE/" sample.txt

If you want to replace multiple substrings, you can specify multiple scripts.


$ sed -e "s/apple/APPLE/" -e "s/orange/ORANGE/" sample.txt

Delete rows

Specify "d" to delete the specified row. For example, to delete line 2 would be "2d".


$ sed -e '2d' sample.txt

In addition, you can delete multiple lines, as shown below by deleting lines 1 through 3.


$ sed -e '1,3d' sample2.txt


Related articles: