我在CentOS 5.5上使用bash。 我有一个由空格分隔的string,string只包含字母和数字,这个string可能有额外的空间,例如, "words"
和"string"
之间有超过1个空格:
$exmple= "This is a lovey 7 words string"
我想删除长度小于2的单词,在这个例子中,单词"a"
和"7"
需要被删除。 并删除所有额外的空间,只有一个词之间的一个空格。
所以string变成:
"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
sed很好地做到这一点:
example="This is a lovey 7 words string" echo $example | sed -e 's/ [a-zA-Z0-9]\{1\} / /g'
sed -e 's/ [a-zA-Z0-9] / /g'
不会删除两个或更多的空格。
这会:
echo "This is a lovey 7 words string" | sed 's/ [a-zA-Z0-9 ] / /g'
这将从开始或结束中删除任何空格:
echo " This is a lovey 7 words string " | sed 's/ [a-zA-Z0-9 ] / /g' | sed 's/^ *\| *$//g'
awk
也可以使它:
$ awk '{for (i=1; i<=NF; i++) s=(length($i)>2? s($i)FS : s); print s}' <<< "This is a lovey 7 words string" This lovey words string
这个想法是遍历字符串的所有字段,存储那些大于给定大小的字段。 最后,打印存储的字符串。
for (i=1; i<=NF; i++)
遍历所有字段。 s=(length($i)>2? s($i)FS : s)
如果单词的长度大于2,则将其附加到当前句子。 否则,不。 print s
打印最后的字符串。