How to Use sed to Append Text at End of Each Line


Often you may want to use sed to append specific text to the end of each line in a file.

You can use the following basic syntax to do so:

sed s/$/_city/ cities.txt > cities_new.txt

This particular example appends the text _city to the end of each line in a file named cities.txt and saves the output to a new file named cities_new.txt.

Here is what the various sed commands do:

  • The s command is used to substitute one pattern for another pattern
  • The $ character is used to match the end of each line
  • We then specify that the end of the line should contain the text _city
  • The > command is used create a new file

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

Example: Use sed to Append Text at End of Each Line

Suppose we have a file named cities.txt that contains the names of various U.S. cities.

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

Suppose that we would like to append the text _city to the end of each line in the file and save the results to a new file.

We can use the following syntax to do so:

sed s/$/_city/ cities.txt > cities_new.txt

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

sed append to end of each line in file

Notice that when we use the cat command to view the contents of the cities_new.txt file that each line has the text _city appended to the end of it, just as we specified.

Related Tutorials

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

How to Use sed to Insert a Line After Match
How to Use sed to Insert Line at Specific Line Number
How to Use sed to Delete Specific Line Numbers from File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply