假设我有一个这样的字符串:
string=" this is a string "
删除重复空格并获取以下字符串的最简单方法是什么:
string="this is a string"
假设我有一个这样的字符串:
string=" this is a string "
删除重复空格并获取以下字符串的最简单方法是什么:
string="this is a string"
这条线应该适用于给定的例子:
awk '$1=$1' <<< $string
见测试:
kent$ x=" this is a string "
kent$ awk '$1=$1' <<< $x
this is a string
无需使用像 Awk 这样的外部二进制文件。你可以单独在 Bash 中做到这一点。
string=" this is a string "
IFS=' ' read -a __ <<< "$string"; string="${__[@]}"
echo "$string"
this is a string
另一种解决方案:
shopt -s extglob ## need to be set only once.
string=${string##*([[:blank:]])}; string=${string%%*([[:blank:]])}; string=${string//+([[:blank:]])/ }
或者只是特定于空格 ( $'\x20'
)
string=${string##*( )}; string=${string%%*( )}; string=${string//+( )/ }
使用 echo 的解决方案:
string=$(echo $string)
逐个字符遍历字符串。每当您获得两个连续的空格时,将数组向后移动一个字符
使 shell 的分词工作为您工作(假设 为 的默认值IFS
)。
string=" this is a string "
arr=($string)
printf -v string2 "%s" "${arr[*]}"
echo _${string2}_
_this is a string_