sed tutorial: sed append command

The sed append command is the most commonly used function except sed mode replacement. It can help us add a new line before or after the specified matching line.

This article will share with you whether it is sed before or after the pattern matching line.

The following content is the content of the test file. We operate this file to demonstrate the sed append command.

1. sed append command.
2. sed appends a new line before a specific line number.
3. sed appends a new line after a specific line number.
4. sed appends new lines before the lines that match the regular pattern.
5. sed appends new lines after the lines that match the regular pattern.
6. sed append new line to end of file.

sed appends a new line before a specific line number

In the following example, we will use the sed i option command to share with you how to append a new line before a specific line number in the file.

Sed append a new line to the first line of the file with i option

The following sed command will add a new line at the beginning of the file.

➜  ~ sed '1i sed append a new line to the first line of the file' test.txt

Add a new line before the second line with sed i option

➜  ~ sed '2i sed append a new line before the second line' test.txt

Add a new line before the last line with sed i option

➜  ~ sed '$i sed append a new line before the last line' test.txt

sed appends a new line after a specific line number.

In the following example, we will use the sed a option command to share with you how to add a new line after a specific line number in the file.

Add a new line after the second line with sed a option

➜  ~ sed '2a sed append a new line after the second line' test.txt

Sed append new line to end of file with a option

The following sed command will add a new line at the end of the file.

➜  ~ sed '$a sed append a new line after the last line' test.txt

sed append a new line before match

In the following example, we will use the sed i command to share with you how to add new lines before matching lines in the file.

➜  ~ sed '/append command/i add a new line before match' test.txt

sed append a new line after match

In the following example, we will use the sed a command to share with you how to add new lines after matching lines in the file.

➜  ~ sed '/append command/a add a new line after match' test.txt

Add a Comment

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