Rahul Popuri
Rahul Popuri

Reputation: 79

How do I add a literal newline character while using sed's string replace?

Let me explain the scenario I am facing: I have a perl file that, among other things, creates a 'header' string used by another process. This is defined in the perl script (script.pl) as:

$str = "START\n" .
"PARAM1=blah\n" .
"PARAM2=blah2\n" .
"PARAM3=blah3\n";

etc

I need to modify the value of $str by appending more values from a bash script, so I thought I would use sed. This is what I have so far:

str_new="\"NEWPARAM1=blah\" .\n\"NEWPARAM2=blah2\" .\n";
sed -i "/START/{n;s/^/$str_new/}" script.pl

This sort of works, what I'm getting is:

$str = "START\n" .
       "NEWPARAM1=blah" .
       "NEWPARAM2=blah2" .
       "PARAM1=blah\n" .
       "PARAM2=blah2\n" .
       "PARAM3=blah3\n";

However, what I need is the literal '\n' to appear as well after the new parameters I've added:

$str = "START\n" .
       "NEWPARAM1=blah\n" .
       "NEWPARAM2=blah2\n" .
       "PARAM1=blah\n" .
       "PARAM2=blah2\n" .
       "PARAM3=blah3\n";

I've tried using '\n', \n in the sed replace clause but no luck. Any help would be appreciated

Upvotes: 1

Views: 279

Answers (2)

Cole Tierney
Cole Tierney

Reputation: 10324

I would consider using a heredoc in the perl to simplify the problem:

$str = <<EOT;
START
PARAM1=blah
PARAM2=blah2
PARAM3=blah3
EOT

Upvotes: 0

anubhava
anubhava

Reputation: 786111

Use it like this:

str_new='"NEWPARAM1=blah\\n" .\n"NEWPARAM2=blah2\\n" .\n'
sed -i.bak "/START/{n;s/^/$str_new/;}" script.pl

cat script.pl
$str = "START\n" .
"NEWPARAM1=blah\n" .
"NEWPARAM2=blah2\n" .
"PARAM1=blah\n" .
"PARAM2=blah2\n" .
"PARAM3=blah3\n";

Upvotes: 1

Related Questions