Sed, how to replace one line with two lines?

I am trying to replace 1 line with two 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 continued to complain, saying that the unknown parameter is `s'.

Can anybody help?

Thanks!

+7
source share
3 answers

Try it if you are in bash:

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

Strange, huh? But it seems to work. Perhaps sed cannot handle the new line correctly, so it needs to escape with another backslash, such that \\ , which will be the only \ before moving to sed.

Also note that you did not pass the extension to -i .


Edit

Just found another solution. Since when going to sed (otherwise he thinks it is a command line terminator) the escaping should be escaped, you can use single quotes and return, just insert the backslash before entering a new line.

 $ echo test | sed 's/test/line\ > line' line line 
+8
source

Or instead of searching and replacing ( s command), searching and adding ( a )

 sed -i '/Your are good/a You are the best' filename 
+7
source

EDIT:

Perhaps my favorite method nowadays is to use a special character instead of '\ n'. Citation rules become such a headache when you walk around a line. But if you pack your string, say | instead of \n and _ instead , then you have a truly portable representation that you can pass into functions, etc.

Here is an example:

 whatAmI=$( printf "Wow oh wow\nYou are good\n"| \ sed -e 's#\(You are \)\(good\)#\1\2|\1the best#g' | \ tr '\n' '|' | tr ' ' '_' ) 

Result:

Wow_oh_wow | You_are_good | You_are_the_best |

To "unzip" your compressed line, simply pass it through the same tr , but with the reversal of the order.

i.e.

 echo "$whatAmI" | tr '|' '\n' | tr '_' ' ' 

Result

Wow wow
You're good
You are the best


In addition to the above strategies (using appen - /a and splitting with \\\n ) you can also do this:

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

In some ways, I prefer Glenn Jackman's decision, as it is more true to intent.

But I find this strategy useful, as you can also use it to pass in variables in bashscripts. If you are not going to use the variable more than once, it will be cleaner than -v , for example.

 whatYouAre="okay" sed -i 's/You are good/You are good'"\n"' You are '"${whatYouAre}"'/g' /output.txt 

(Note: single quotes also work for \n , but not for passing to vars, as this requires interpretation.)

+1
source

All Articles