0

Suppose I have a string like this:

string=" this is a string " 

What is the simplest way to remove duplicated whitespaces and get the following string:

string="this is a string" 

5 Answers 5

3

this line should work for the given example:

awk '$1=$1' <<< $string 

see test:

kent$ x=" this is a string " kent$ awk '$1=$1' <<< $x this is a string 
Sign up to request clarification or add additional context in comments.

5 Comments

much better than my sed -e 's/^ *//g' -e 's/ *$//g' which only solved 2 of the three parts... +1
@FredrikPihl it could be shorter s/^ *\| *$// but we still need s/ \+/ /g
Thanks! Is there a way to achieve this without using awk?
yes, other tool, or bash itself. Personally I just thought awk would be the simplest. @Doppelganger
cat <<< $string is also simple
2

No need to use external binaries like Awk. You can do that in Bash alone.

string=" this is a string " IFS=' ' read -a __ <<< "$string"; string="${__[@]}" echo "$string" this is a string 

Another solution:

shopt -s extglob ## need to be set only once. string=${string##*([[:blank:]])}; string=${string%%*([[:blank:]])}; string=${string//+([[:blank:]])/ } 

Or just specific to spaces ($'\x20')

string=${string##*( )}; string=${string%%*( )}; string=${string//+( )/ } 

4 Comments

echo $string gives me {__[@]} bash version 4.2.45
@FredrikPihl Sorry forgot $. I changed the parameter's name from string.
yeah, I saw that 2 seconds after I hit send. Nice usage of array and the IFS variable but you have to agree that the awk solution is cleaner :-)
@FredrikPihl Only slower and needs a subshell :)
1

Solution using echo :

string=$(echo $string) 

Comments

0

Traverse the string character by character. Whenever you get two consecutive whitespaces, shift the array one character backwards

Comments

0

Make the shell's word-splitting work for you (assuming a default value for IFS).

string=" this is a string " arr=($string) printf -v string2 "%s" "${arr[*]}" echo _${string2}_ _this is a string_ 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.