我在 CentOS 5.5 上使用 bash。我有一个用空格分隔的字符串,并且该字符串只包含字母和数字,并且这个字符串可能有多余的空格,例如之间有超过1个空格"words"
and "string"
:
$exmple= "This is a lovey 7 words string"
我想删除长度小于2的单词,在本例中是单词"a"
and "7"
需要删除。并删除所有多余的空格,仅一个单词与另一个单词之间的一个空格。
所以字符串变成:
"This is lovey words string"
Edit(基于无聊杀手的sed
answer)
使用纯 Bash:
newstring=${exmple// ? / } # remove one character words
标准化空白:
read newstring <<< $newstring
or
shopt -s extglob
newstring=${newstring//+( )/ }
原来的:
exmple="This is a lovey 7 words string"
for word in $exmple
do
if (( ${#word} >= 2 ))
then
newstring+=$sp$word
sp=' '
fi
done
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)