user3529352 user3529352 - 6 days ago 6
Bash Question

Replace single line with multiline code and vice versa

I want to replace a single line,

string1
, with a snippet of code.
I could do it with a sed command:

sed -i "s|..|a very long code|g"


The code could cover three rows. However, our code style requires the code must be under certain columns in each row. For formatting, I used "Enter" key press. It seems "Enter" keypress would lead to "unterminated s command" error.

Is there any good bash command to do it?

Also, how to replace this multiline code with a single line? The code has some
%
,
*
and some regex characters. Seems pattern space should not have them.

Answer

Use \n to indicate linebreaks.

:~> sed "s|string1|#include \"test.h\"\n#include \"release.h\"|g"

Would print

#include "test.h"
#include "release.h"

You could enter spaces as required

:~> echo sleep100 | sed "s|sleep100|\
for (int i=0; i< 100; i++){\n\
sleep(1);\n}|g"

Would print a formatted loop construct

for (int i=0; i< 100; i++){
   sleep(1);
}

With a bit of roundabout coding you could even keep the necessary amount of whitespace in the beginning of each line of the sed command.

:~> bs4="$(printf '%b' '\b' '\b' '\b' '\b')" ;\
    echo sleep100 | sed "s|sleep100|\
    ${bs4}for (int i=0; i< 100; i++){\n\
    sleep(1);\n}|g"

The essence of the trick is to get over the limitation of sed that interprets \b escape differently. Instead of using the escape sequence we plant actual backspace characters to gobble up the extra spaces.

P.S. You could have special characters such as $, % and * in the replacement expression as soon as you escape them with backslashes as \$, \% and \* respectively.

Comments