Reputation: 14098
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"
Upvotes: 0
Views: 127
Reputation: 23374
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_
Upvotes: 0
Reputation: 75458
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//+( )/ }
Upvotes: 2
Reputation: 56
Traverse the string character by character. Whenever you get two consecutive whitespaces, shift the array one character backwards
Upvotes: 0
Reputation: 195029
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
Upvotes: 3