I am trying to comment out a matched string in a file and add new line right below the matched string. Is there any way to do this ? May be using sed or awk.

For example,

line1 is good
line2 is bad
line3 is to be commented
line4 is final

I want to match line3 here (not using line number) and comment it out and add new line right below it.

Expected output

line1 is good
line2 is bad
#line3 is to be commented
new line
line4 is final

Output to console:

sed '/^line3/s/^\(.*\)$/#\1\n/' testdata.txt

Replace in file and create backup:

sed -i.bak '/^line3/s/^\(.*\)$/#\1\n/' testdata.txt

Replace in file:

sed -i '/^line3/s/^\(.*\)$/#\1\n/' testdata.txt


General syntax for sed:


Pattern is ^line3 (replace it with your pattern)

Action is s/^\(.*\)$/#\1\n/

s - sed replace command (s/pattern1/pattern2/)

^(.*)$ - RegEx pattern to match all line

#\1\n - replace line with: hash (#) + RegEx back reference (\1) + new line (\n)

Remember to:

  • add backslash before parentheses
  • surround all line with parentheses
| improve this answer | |
  • Thanks. But can you please tell me the command for the expected output I ve mentioned so that I ll get a better idea. – Unnikrishnan May 29 '17 at 10:25
  • @Unnikrishnan I've added 3 scenarios. – Tomasz Jakub Rup May 29 '17 at 10:35
  • I mean the syntax to replace the "line 3" with new line commenting other – Unnikrishnan May 29 '17 at 11:52
  • @Unnikrishnan Pleas explain. My solution works fine on Your example data – Tomasz Jakub Rup May 29 '17 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.