You can use the SED command to replace a character string in a file like the search replacement function of a text processor. The SED command can also delete consecutive lines from the file. Because SED is a stream editor that uses the given file as the input and prints the output to the screen unless it redirects the output to a file. In other words, sed does not change the input file.
The form of the SED command is as follows:
Replace: SED's // G'
Delete: sed ', D'
Let's first look at the replacement example. If you want to replace all lamb in the file poem.txt with ham, the command is as follows:
Cat poem.txt
Mary had a little lamb
Mary fried a lot of Spam
Jack ate a spam sandwich
Jill had a lamb spamwich
Sed's/lamb/Ham/G' poem.txt
Mary had a little ham
Mary fried a lot of Spam
Jack ate a spam sandwich
Jill had a ham spamwich
In the string enclosed by single quotes, "S" indicates replacement (substitute), and "G" indicates global replacement. You can also remove "G" (only replace the string that appears for the first time in each line) or specify a number (Replace the first n times in each line ).
Now let's look at an example to protect the deletion of rows. The value of start and end can be either a row number or a matching pattern. All rows from start to end are removed from the output. In this example, the content starting from row 2nd and containing row 3rd will be deleted:
Sed '2, 3D 'poem.txt
Mary had a little lamb
Jill had a lamb spamwich
In this example, the content starting from row 1st is deleted to the line containing JACK:
Sed '1,/Jack/d' poem.txt
Jill had a lamb spamwich
The most common use of the SED command is to replace one text string with another text string. In fact, the string sed uses to search for and delete is a regular expression. This means that pattern matching can be used like grep. Although it may never be used this way, here is an example. Replace any lamb that appears at the end of a row with ham and store the result in a new file:
Sed's/lamb $/Ham/G' poem.txt> New. File
Sed does not print anything on the screen Because It redirects the output to a file. View the new file new. file and get the following lines:
Cat new. File
Mary had a little ham
Mary fried a lot of Spam
Jack ate a spam sandwich
Jill had a lamb spamwich
Use the man sed command to obtain more information about sed.
This article from the Linux community website (www.linuxidc.com) original link: http://www.linuxidc.com/Linux/2012-04/58860.htm