Bash: How to Add Suffix to Each Line in File


Often you may want to use Bash to add a suffix to the end of each line in a file.

You can use the following syntax to do so:

sed 's/$/ city/g' cities.txt

This particular example will add the suffix ” city” to the end of each line in the text file named cities.txt.

Here is what the various sed commands do:

  • s: Substitutes one pattern for another
  • $: Specifies that the end of the line ( $ ) should be replaced
  • city-: Specifies that a space followed by “city” should be used as replacement
  • g: Specifies that substitutions should be made “globally”, i.e. for all occurrences

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

Example: How to Add Suffix to Each Line in File Using Bash

Suppose that 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:

Now suppose that we would like to add the suffix ” city” to the end  of each line in the file.

We can use the following syntax to do so:

sed 's/$/ city/g' cities.txt

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

Bash add suffix to each line in file

Notice that the suffix ” city” has been added to the end of each line in the file.

Also note that you could use the > command to save these results to a new file:

sed 's/$/ city/g' cities.txt > new_cities.txt

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

Notice that when we use the cat command to view the contents of the new file named new_cities.txt we can see that the suffix ” city” has been added to the end of each line in the file.

Related Tutorials

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

Bash: How to Extract Text Between Two Strings
Bash: How to Replace Multiple Characters in String
Bash: How to Replace All Occurrences of String in File

Leave a Reply