I'd like to use bash to replace multiple adjacent spaces in a string by a single space. Example:
Original string:
"too many spaces."
Transformed string:
"too many spaces."
I've tried things like "${str//*( )/.}"
or awk '{gsub(/[:blank:]/," ")}1'
but I can't get it right.
Note: I was able to make it work with <CMD_THAT_GENERATES_THE_INPUT_STRINGH> | perl -lpe's/\s+/ /g'
but I had to use perl to do the job. I'd like to use some bash internal syntax instead of calling an external program, if that is possible.
Another simple
sed
expression using BRE is:For example:
There are a number of ways to skin the cat.
If the enclosed whitespace could consist of mixed
spaces
andtabs
, then you could use:And if you simply want to have bash word-splitting handle it, just echo your string without quotes, e.g.
Continuing with that same thought, if your string with spaces is already stored in a variable, you can simply use
echo
unquoted within command substitution to have bash remove the additional whitespace for your, e.g.Here is a way to do this using pure
bash
andextglob
:[[:blank:]]
matches a space or tab character+([[:blank:]])
matches one or more of the bracket expression (requiresextglob
)Using
tr
:man tr
:Edit: Oh, by the way:
Edit 2: On the performance:
Over 7 seconds?! How is that even possible. Well, this mini laptop is from 2014 but still. Then again: