开发者

Not able to write a proper regular expression to remove multiple spaces

$ echo "Anirudh   Tomer" | sed 's/ +/ /g'
Anirudh   Tomer

I was expecting it to remove those 3 spaces between Anirudh and Tomer and give me result as "Anirudh Tomer"

I am a beginner. Thanks in advance 开发者_StackOverflowfor the help.


You need to enable sed's extended regexp support with the -r flag.

echo "Anirudh   Tomer" | sed -r 's/ +/ /g'

In extended regular expressions, the ?, + and | metacharacters must not be escaped (see wikipedia). The * metacharacter works because it belongs to the basic regular expressions.


Similar to VIM regex, you need to escape the + quantifier with a backslash:

sed 's/ \+/ /g'


echo "Anirudh   Tomer" | tr -s ' '
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜