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 %?) Commented May 17, 2019 at 10:54

2 Answers 2

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. Commented May 17, 2019 at 11:37
  • The answer assumes GNU sed. Commented May 17, 2019 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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.