Use sed to Append Text to End of Each Line Matching Pattern


Often you may want to use sed to append text to the end of each line that matches a specific pattern.

You can use the following syntax to do so:

sed '/A00/ s/$/_new/' employees.txt

This particular example will append the text _new to the end of each line that contains the pattern A00 in the file named employees.txt.

Here is how this syntax works:

  • First, we match all lines that contain the pattern A00
  • Then, we use the s command to perform a substitution
  • We use the $ character to match the end of the line and replace the ending with _new

The following example shows how to use this syntax in practice.

Example: Use sed to Append Text to End of Each Line Matching Pattern

Suppose that we have a file named employees.txt that contains the ID values for various employees at some company.

We can use the cat command to view the contents of this file:

Now suppose that we would like to append the text _new to the end of each line that contains the pattern A00.

We can use the following syntax to do so:

sed '/A00/ s/$/_new/' employees.txt

The following screenshot shows how to use this syntax in practice:

sed append text to end of each line matching pattern

Notice that the text _new has been appended to the end of each line that contains the pattern A00 in the file.

Note that if you would like to save these changes to the file in-place then you can add the -i flag as follows:

sed -i '/A00/ s/$/_new/' employees.txt

This will save the changes to the employees.txt file in-place.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Insert Line at Specific Line Number
How to Use sed to Insert Empty Line in a File
How to Use sed to Insert Line with Leading Spaces
How to Use sed to Insert a Line After Match

Leave a Reply