1

I would like to comment a line 2 in abc.c and add the text New second line in line 3 of the file.

abc.c:

First line
Second line
Third line

My modified file should look like

First line
//Second line
New second line
Third line

I have tried using the command

sed 's/Second line/\/\/Second line\
New second line/g' abc.c > tmp.c && mv tmp.c abc.c

But it gives the error as "sed command garbled" on sunOS 5.10

Can anyone please tell me what's the correct command to use?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Kripalini
  • 11
  • 1

2 Answers2

0

Try:

sed "s/Second line/\/\/&\\
New second line/g" abc.c > tmp.c && mv tmp.c abc.c
Nick
  • 4,820
  • 18
  • 31
  • 47
0

sed -i.bak -e"s/Second line/\/\/&\nNew second line/;" abc.c

Afterwards content of file:

First line  
//Second line  
New second line  
Third line  
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • Doing a 'p' duplicates every line in the file as well, which then has to be suppressed with the '-n'. What's the point? '\n' doesn't work on all platforms (e.g. macOS), whereas the embedded literal newline does. The {} are unnecessary. – Nick Apr 13 '17 at 07:13
  • I did not manage to use your answer on my machine, (GNU sed version 4.2.1 on Windows). Probably because I do not know how to use the embedded newline. I would appreciate learning that, based on your explanation. My version is a one-liner which works on my machine. So I thought I provide what works for me, as an alternative answer. I admit the use of `-n` AND `p` is inefficiently redundant. I will edit the answer. Thanks for pointing it out. – Yunnosch Apr 13 '17 at 07:24
  • I think OP might have the same trouble understanding embedded-newlines as I have. So you are probably set for many upvotes (at least an acceptance by OP and an upvote by me) if you explain it. – Yunnosch Apr 13 '17 at 07:28