Operating System - Linux
1820270 Members
3374 Online
109622 Solutions
New Discussion юеВ

Re: sed new line not working

 
ionut_lascu
Advisor

sed new line not working

I want to insert in a file after #test
2lines line1 line2 sed 's/#test/&\n'line1"\n"line2'/' file

Not working.
My output:
#testnline1nline2
1
2
Sed version is 3.02
What is wrong ?
5 REPLIES 5
Fredrik.eriksson
Valued Contributor

Re: sed new line not working

Hi

sounds wierd that the \n doesn't work... it should work with any version of sed imo.

But, I'm not sure this will work since I don't have anything to test it on :P
$~> sed "/#test/ a\line1\;a\line2\" file

Otherwise this should also work:
$~> sed -e "/#test/ a\line1\" -e "/line1/ a\line2\" file

a\ is append after matched line.

Hope this helps you :)

Best regards
Fredrik Eriksson
ionut_lascu
Advisor

Re: sed new line not working

not working.
On sed 4.02 works fine.
sed 's/#test/&\n'line1"\n"line2'/' file

On sed 3.02 \a not working.
Fredrik.eriksson
Valued Contributor

Re: sed new line not working

Too clarify... it's not \a, it's a\.
The part "/#test/" will search for any occurance of #test. "a\Line1" will append after the matched occurance the trailing characters that is listed after "\".

But as he said, didn't work... I tried it last night and found that \n is probably the only reasonable way unless you do 2 sed's.

$~> sed -i "/#test/ a\Line1" file.txt
$~> sed -i "/Line1/ a\Line2" file.txt

but since "-i" parameter changes the original file maybe it's better to "-e" and redirect the output to a new file like this

$~> sed -e "/#test/ a\Line1" file.txt > newfile.txt
$~> sed -i "/Line1/ a\Line2" newfile.txt

But if your version works now with \n, I would say it's simpler too use my method described above.

$~> sed -e "/#test/ a\Line1\nLine2" file.txt

Best regards
Fredrik Eriksson
ionut_lascu
Advisor

Re: sed new line not working

$~> sed -i "/#test/ a\Line1" file.txt
sed: invalid option -- i

$~> sed -e "/#test/ a\Line1" file.txt > newfile.txt
sed: -e expression #1, char 11: Extra characters after command

My version works with \n only on 4.02 version, I need to work on another box with 3.02 sed version

David C. Brown
New Member

Re: sed new line not working

I have tried this on a couple of boxes here:

sed 's/#test/&\^Jline1\^Jline2/' testfile

Where it says ^J, do [CTRL+V][CTRL+J].

David