Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

-->

Content

<!--

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
add comment

1 Answer

up vote 4 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
add comment

Your Answer

 
discard

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.