1

I am trying to use sed to add a string after a certain pattern but I want to exclude the case where the additional string is already present.

For example:

"text.txt"

Hello
Bar
Hello world!

If I use sed -i -e 's/Hello/Hello world!' text.txt the third line becomes

Hello world! world!

but I would like to keep it intact.

I have found this related question but not all the lines in my file need to be modified.

Has anyone got recipe for this?

  • 3
    In fact, the related question gives you all you need. /Hello world!/ !s/Hello/Hello world!/ – choroba May 2 '18 at 11:24
  • Ah thanks. Goodness me I couldn't make sense of this. – Jacques Gaudin May 2 '18 at 11:30
  • Please @choroba post it as an answer with a line of explanation so it can be accepted by the OP. – simlev Jun 6 '18 at 13:30
2

The answer to your question is in kind of hidden in one of the answers in the related question:

/Hello world!/ ! s/Hello/Hello world!/

The first part of it is an "address", i.e. the following command only applies to lines matching it. The ! negates the condition, i.e. the command will only be applied to lines not matching the address. So, in other words, Replace Hello by Hello world! on lines that don't contain Hello world!.

  • This might be more clearly put as /Hello world!/! s/Hello/Hello world!/ (note the positioning of the !)... this way the negation is associated with the address, rather than with the substitution. – Attie Jun 6 '18 at 15:33
2

You could use the explicit start and end of line anchors (^ and $):

$ sed -e 's/^Hello$/Hello world!/' <<EOF
> Hello
> Bar
> Hello world!
> EOF
Hello world!
Bar
Hello world!

This could also be somewhat improved for readability / brevity by using \0 which substitutes the whole match... This way you don't need to repeat the Hello:

$ sed -e 's/^Hello$/\0 world!/' <<EOF
> Hello
> Bar
> Hello world!
> EOF
Hello world!
Bar
Hello world!

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.