1

I am trying to use sed to substitute a string taking into account an whitespace.
Example:

Hello          World

to be replaced by

Hello George  

I tried:

sed -e 's/Hello[:space]+World/Hello George/' ./infile > outFile

but it does not work.

How can I fix this?

1
  • [:space:] and not [:space], I think. Also, [[:space:]], otherwise the square brackets will be misinterpreted. Commented Oct 22, 2012 at 9:57

3 Answers 3

4
sed -e 's/Hello[[:space:]]\+World/Hello George/' ./infile > outFile

or

sed -e 's/Hello \+World/Hello George/' ./infile > outFile

Note: In OSX, you'll need

sed -E 's/Hello +World/Hello George/' ./infile > outFile
Sign up to request clarification or add additional context in comments.

2 Comments

This works.Is there a case I would prefer using \+ over [[:space:]]?Is it available always?
I think [[:space:]] includes tabs as well and maybe a few other, whereas ` ` is just... well... single space. Both should always be available (in sed)
1

may be you can go with perl:

perl -pe 's/Hello\s*World/Hello Goerge/g'

Comments

0

You can use

sed -e 's/Hello\s\+World/Hello George/' ./infile > outFile

The code for space is \s, same as \w would be for word characters.

4 Comments

Nope, you don't have to use that form, the [:space:] can be used as well and is better in some cases (unicode, changed locales etc.)
@alestanis: I have explained above.
@January you're right about the have to. I edited my answer.
@alestanis: but you have still a problem with the +, which, in "standard" sed is interpreted literally (to have a quantifier, you need to use \+).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.