Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I wish I can grab the first html comment in a file using sed.

Using '/<!--/,/-->/ and having more than one comment block it will match all the content between the first and the last comment block too!

Any advice?

Here a sample:


First comment block




Second comment block


The expected output should be:


First comment block


It should work with single line comments too.

<!-- First comment block -->
share|improve this question
Please post a sample input file and expected output – Guru Jan 18 '13 at 12:37
up vote 5 down vote accepted

You would do something along the lines of:

sed '/<!--/,$!d;/-->/q'

The first command deletes all lines but from the first matching <!-- onwards. And among those that haven't been deleted by the first command, we search for the closing tag and quit (after having printed that line as well).

With perl, to strip the comment tags:

perl -ln0777 -e 'print $1 if /<!--\s*(.*?)\s*-->/'
share|improve this answer
Cool! Could you explain please sed one? – neurino Jan 18 '13 at 12:45
Plain genius. Accepted! Thanks – neurino Jan 18 '13 at 13:30

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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