5

I search a pattern, say 'START OF ARAMBOL' and it is matched in a file. Now I would like to comment every line from the line no 1 to the current matched pattern line no. I have to do it for more than 200 files.

I can do this using perl too but is there any good sed method to do so.

Thanks

1
  • 3
    Please be specific about what constitutes a comment in the context of your files (C-style comment? C++ style? leading # or %?) May 17 '19 at 10:54
4

As a one-liner to demonstrate the concept :

echo -e 'a\nb\nc\nPATTERN\nd\ne\nf' | sed '0,/PATTERN/ s/^/#/'

You just have to adapt to your context :

  • as for the 'PATTERN'
  • I assumed '#' as the commenting character
  • and regarding how you can apply this to all your files. If they all are 'fileXXX.txt', you can run : sed -i '0,/PATTERN/ s/^/#/' file*txt
2
  • 1
    I would stress the assumption (actually reasonable, looking at the question) that the PATTERN is found in each file. This solution will comment any line in files in which PATTERN is not found.
    – fra-san
    May 17 '19 at 11:37
  • The answer assumes GNU sed. May 17 '19 at 15:30
1

Your question asks about sed but includes the gvim tag, so here is an ed/ex answer:

ed file <<EOF
0,/"$pattern"/s/^/"$comment_char"/
wq
EOF

That it looks remarkably like the sed answer is because sed and ex descend from ed

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.