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" 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 sed -e 's/^ *//g' -e 's/ *$//g' which only solved 2 of the three parts... +1s/^ *\| *$// but we still need s/ \+/ /gcat <<< $string is also simpleNo 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//+( )/ } {__[@]} bash version 4.2.45string.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_