How to remove consecutive space in shell bash linux?

bash, linux, shell

Solution

Use `tr` with `-s` to squeeze repeated characters:

$ echo "$str" | tr -s ' '
toto1 toto2 toto3 toto4 toto5 toto6

or

$ tr -s ' ' <<< "$str"
toto1 toto2 toto3 toto4 toto5 toto6

Another funny approach is the one suggested by glenn hackman here. As he says,

Take advantage of the word-splitting effects of not quoting your variable

Example:

$ echo "$str"
toto1 toto2  toto3   toto4 toto5      toto6
$ echo $str
toto1 toto2 toto3 toto4 toto5 toto6

So you can save the converted string with:

new_str=$(echo $str)

Problem

I have string containing words. Between the words there is a random number of spaces ``` str="toto1 toto2 toto3 toto4 toto5 toto6" ``` How I can remove duplicated spaces and keep only one space between words?

Original source

Related problems