Wednesday, April 13, 2022

[SOLVED] sed, how to replace one line with 2 line?

Issue

I am trying to replace 1 line with 2 lines using sed in Debian and here is what I came up with:

sed -i 's/You are good/You are good\n You are the best/g' /output.txt

However, when I do this, sed kept complaining saying "unknown option to s".


Solution

Try this if you're in bash:

sed -i.bak $'s/You are good/You are good\\\nYou are the best/g' /output.txt

Strange, eh? But seems to work. Maybe sed can't handle the newline correctly so it needs to be escaped with another backslash, thus \\ which will become a single \ before going to sed.

Also, note that you were not passing an extension to -i.


Edit

Just found another solution. As the newline needs to be escaped when passing to sed (otherwise it thinks it's a command terminator) you can actually use single quotes and a return, just insert the backslash before entering the newline.

$ echo test | sed 's/test/line\
> line'
line
line


Answered By - sidyll
Answer Checked By - David Marino (WPSolving Volunteer)