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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With