How to Use sed to Add Comma to End of Every Line in File


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

You can use the following syntax to do so:

sed 's/$/,/' cities.txt

This particular example will add a comma to the end of each line in the file named cities.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 a comma ( , )

Note that you could also use the following syntax to add a comma to the end of each line except for the last line in the file:

sed '$!s/$/,/' cities.txt

The following example shows how to use each of these methods in practice.

Example: Use sed to Add Comma to End of Every Line in File

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 add a comma to the end of every line in the file.

We can use the following syntax to do so:

sed 's/$/,/' cities.txt

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

sed add comma to end of every line

Notice that a comma has been added to the end of each line in the file.

Suppose that we would like to add a comma to the end of each line except for the last line.

We can use the following syntax to do so:

sed '$!s/$/,/' cities.txt

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

sed add comma to end of each line except last line

Notice that a comma has been added to the end of each line in the file except for the last line.

Feel free to use whichever method you prefer.

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