我在 CentOS 5.5 上使用 bash。我有一个由空格分隔的字符串,该字符串只包含字母和数字,并且这个字符串可能有额外的空格,例如 "words"
和 "之间有超过 1 个空格字符串"
:
$exmple= "This is a lovey 7 words string"
我想删除长度小于2的单词,本例中需要删除单词"a"
和"7"
。并删除所有多余的空格,一个单词和另一个单词之间只有一个空格。
所以字符串变成:
"This is lovey words string"
最佳答案
编辑(基于 ennuikiller 的 sed
回答)
使用纯 Bash:
newstring=${exmple// ? / } # remove one character words
规范化空白:
read newstring <<< $newstring
或
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
关于linux - bash中删除长度小于2的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4417663/