Skip to content
Advertisement

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

Advertisement

Answer

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/MynReplacementnText/' file
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement