This works

echo "         HELLO   x=10" |sed 's/ *\HELLO \+/HELLO /g'

removes continuous space before hello and after word "HELLO"

but this doesn't

echo "         WHERE     x=10" |sed 's/ *\WHERE \+/WHERE /g'

i have tried to escape \w with \w like below

echo "         WHERE     x=10" |sed 's/ *\\"WHERE" \+/\"WHERE" /g'

but even this is not working. What is wrong.


Why are you escaping the H and the W ?

\H and \W have specific meanings, and they are different from H and W .

echo "         WHERE     x=10" |sed 's/ *WHERE \+/WHERE /g'

Just drop the \ before the words.

echo "         WHERE     x=10" |sed 's/ *WHERE \+/WHERE /g'
WHERE x=10

The \ in regular expressions is used as an escape character for various type of matches.

The \w is used to find a word character, i.e. a character from a-z, A-Z, 0-9, including the _ (underscore) character.

As an upper case version negates a match, your \W means don't match a single character, which obviously makes the regex fail for your input string.

Try for example:

echo "         {HERE     x=10" |sed 's/ *\WHERE \+/WHERE /g'
WHERE x=10

it works because { is matched by \W (as { is NOT a word character)!

  • Thanks ,can't upvote , don't have that reputation . actually \ worked with HELLO but not with WHERE and confused me. – etl_devs Oct 10 '18 at 15:13
  • 1
    @etl_devs that's because \h matches whitespace and then \H not whitespace which means the H in HERE gets matched – Mr Shunz Oct 10 '18 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.