Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to replace a string with the sed command in Linux

Shulou Source: shulou.com Published: 2022-06-01 23:03:23 09月23日 Update

This article is about how to use the sed command to replace strings in Linux. I think it is very practical, so I share it with you. I hope you can get something after reading this article.

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

$sed s / replaced target string / replaced string / file name

Below we replace the string "sample.txt" written as "appleorangemelon".

$sed s/orange/ORANGE/ sample.txt

The execution result is

AppleORANGEmelon

Replace and output the string.

In addition, 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 overwrite the contents of the actual file

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

Options used by the sed command

The command option description-e is replaced with the specified script-f file to add the contents of the script file described in the specified file-r uses extended regular expressions

Use of the sed command

Replace all lines

In the format described earlier, only the first matching string is replaced, even if there is a string in one line that matches multiple replacement object strings.

Therefore, to replace all matching strings:

$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 Row

Specify "d" to delete the specified row. For example, to delete the second line is "2d".

$sed-e '2d' sample.txt

In addition, you can delete multiple lines, as shown below: delete lines 1 to 3.

The above $sed-e '1sed 3d' sample2.txt is how to replace strings with the sed command in Linux. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Character string command file content multiple result script more format knowledge article output practical actual object that is work meeting beginning file name Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi MariaDB OPPO Reno Huawei Shulou Information