Use sed to Convert Multiple Lines into One Comma Separated Line


Often you may want to use sed to convert multiple lines into one comma separated line.

You can use the following basic syntax to do so:

cat employees.txt | xargs | sed -e 's/ /,/g'

This particular example converts all lines from the text file named employees.txt into a single comma separated line.

Here is what this syntax does:

  • The cat command displays all lines from the file
  • The xargs command converts all of the lines to one space-separated line
  • The sed s command substitutes each space with a comma, and the g command specifies that this substitution should be made “globally”, i.e. for each occurrence of a space

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

Example: Use sed to Convert Multiple Lines into One Comma Separated Line

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:

Suppose that we would like to convert all of the lines from the file into a single comma-separated line.

We can use the following syntax to do so:

cat employees.txt | xargs | sed -e 's/ /,/g'

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

sed convert multiple lines into one comma separated line

Notice that this produces a single line in which the values from each line are separated by commas.

Note that you could also use the following syntax if you would like each line to be separated by a comma with a space after it:

cat employees.txt | xargs | sed -e 's/ /, /g'

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

Notice that this produces a single line in which the values from each line are separated by a comma and a space.

Feel free to use whichever approach you prefer.

Related Tutorials

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

How to Use sed to Replace All Occurrences of Pattern
How to Use Case-Insensitive Search and Replace in sed
How to Use sed to Replace All Text After Match

Leave a Reply