Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed, how to replace one line with 2 line?

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".

like image 277
AZhu Avatar asked Aug 16 '11 22:08

AZhu


2 Answers

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
like image 185
sidyll Avatar answered Oct 08 '22 14:10

sidyll


Or, instead of search and replace (s command), search and append (a command)

sed -i '/Your are good/a You are the best' filename
like image 45
glenn jackman Avatar answered Oct 08 '22 15:10

glenn jackman