Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove consecutive space in shell bash linux? [duplicate]

Tags:

linux

bash

shell

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?

like image 576
MOHAMED Avatar asked Sep 15 '25 01:09

MOHAMED


1 Answers

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)
like image 120
fedorqui 'SO stop harming' Avatar answered Sep 17 '25 16:09

fedorqui 'SO stop harming'