Michael Shalmi
Michael Shalmi

Reputation: 35

How to stop newline chars from escaping OLD gnu sed command

I am trying to replace a line in a file with multiple lines. When I had only one new line char ( \'$'\n ). it worked fine, however when I use two of them, it escapes my sed and the file wont run anymore.

sed 's/TextImLookingFor/My\'$'\nReplacement\'$'\nText/g' /path/to/File.txt

File.txt:

This is a file
TextImLookingFor
look at all this text

DesiredOutput

This is a file
My
Replacement
Text
look at all this text

Actual Output

unexpected EOF while looking for matching ''''
syntax error: unexpected end of file

Upvotes: 2

Views: 54

Answers (3)

Etan Reisner
Etan Reisner

Reputation: 81052

The problem with this command

sed 's/TextImLookingFor/My\'$'\nReplacement\'$'\nText/g' /path/to/File.txt

is that it isn't parsing the way you expect it is.

You cannot escape a single quote inside a single quoted string. You can escape a single quote inside a $'...' quoted string however (I'm not really sure why).

So the above command does not parse this way (as you might expect):

[sed] [s/TextImLookingFor/My\'$[\nReplacement\'$]\nText/g] [/path/to/File.txt]

instead it parses this way:

[sed] [s/TextImLookingFor/My\]$[\nReplacement\'$]\nText/g' [/path/to/File.txt]

with a mismatched single quote at the end and an unquoted \nText/g bit.

That is the cause of your problem.

If you can't just use \n in your replacement (your version of sed doesn't support that) and you need to use $'\n' then you would need to use something like

sed 's/TextImLookingFor/My\'$'\nReplacement\\'$'\nText/g' /path/to/File.txt

Upvotes: 0

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed '/TextImLookingFor/c\My\nReplacement\nText' file

Upvotes: 1

anubhava
anubhava

Reputation: 786291

Using older BSD sed you can do:

sed $'s/TextImLookingFor/My\\\nReplacement\\\nText/' file
This is a file
My
Replacement
Text
look at all this text

This should work with newer gnu-sed as well. However newer gnu-sed may just need:

sed 's/TextImLookingFor/My\nReplacement\nText/' file

Upvotes: 3

Related Questions