How to Use sed to Replace Spaces with Commas


Often you may want to use sed to replace spaces with commas in a file.

You can use the following basic syntax to do so:

sed -e "s/ /,/g" players.txt

This particular example will replace all spaces with commas in the file named players.txt.

Note that we used the s command to “substitute” one pattern for another and we used the g command to make this substitution “globally”, i.e. for all occurrences.

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

Example: How to Use sed to Replace Spaces with Commas

Suppose that we have a file named players.txt that contains information about various basketball players.

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

Notice that each of the fields in the file are currently separated by spaces.

Suppose that we would like to replace the spaces on each line with commas instead.

We can use the following syntax to do so:

sed -e "s/ /,/g" players.txt

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

sed replace spaces with commas

Notice that the spaces on each line have been replaced with commas instead.

Note that you can also use the > command to save these changes to a new file if you’d like:

sed -e "s/ /,/g" players.txt > players_new.txt

This particular example would replace all spaces with commas in the file named players.txt and save the results to a new file named players_new.txt.

Related Tutorials

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

How to Use sed to Replace newline with space
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply