1
$ 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 for the help.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

but why does anirudh@anirudh-Aspire-5920:~/Desktop/testing/GET_REQ$ echo "Anirudh Tomer" | sed 's/[ ]*/ /g' A n i r u d h T o m e r works. I mean it should also not work unless I give the -r option
I expanded my answer in order to reflect your comment.
@Andrea: You need to say @Anirudh Tomer so the user is automatically notified of your comment.
@Den thanks for the reminder. Also, I've been reading on meta that the first three letters should also work, so I'm also testing it in this comment. :)
@Anirudh If it is the right answer for you, you should accept it. :) And if you really like it (and the other answers!), upvote it (them).
|
1

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

sed 's/ \+/ /g'

1 Comment

thanks dude!!! your answer solved my problem. However I will prefer to add the -r option to sed now in future to make sed -r 's/ +/ /g' work
0
echo "Anirudh   Tomer" | tr -s ' '

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.