How to Use sed to Replace Multiple Spaces with Single Space


Often you may want to use sed to replace multiple spaces with a single space in a file.

You can use the following syntax to do so:

sed 's/  */ /g' team_list.txt

This particular example replaces all occurrences of multiple spaces with a single space in the file named team_list.txt.

Note that the s command in sed is used to “substitute” one pattern for another pattern and uses the following syntax:

  • s/old_pattern/new_pattern/flags

In this particular example, we specify that we would like to find two spaces followed by anything else ( * ) and replace this pattern with a single space.

We use the g flag to specify that we want to make this replacement “globally”, i.e. for all occurrences of multiple spaces.

The following example shows how to use each method in practice.

Example: Use sed to Replace Multiple Spaces with Single Space

Suppose that we have a file named team_list.txt that contains the names of various basketball teams.

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

Notice that several of the lines have multiple spaces between the pattern team: and the actual team name.

We can use the following syntax to replace all occurrences of multiple spaces with a single space instead:

sed 's/  */ /g' team_list.txt

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

sed replace multiple spaces with one space

Notice that all occurrences of multiple spaces have been replaced with a single space instead.

Note that we could also use the > command to save these results to a new file.

sed 's/  */ /g' team_list.txt > team_list_new.txt

This would replace all occurrences of multiple spaces with a single space and save the results to a new file named team_list_new.txt.

Related Tutorials

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

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 Before Match

Leave a Reply