views:

71

answers:

3

I am looking for a one liner to pull out the first comment block in any file. The comment blocks look like this:

/*
 * This is a 
 * comment block
 */

I've been trying to play with sed, but just can't get it to work right. Help?

+1  A: 

I know it's not exactly what you are asking but it is ridiculously easy to do it with a little python code:

#!/usr/bin/env python
import sys

f = open(sys.argv[1])

incomment = False
for line in f:
  line = line.rstrip("\n")
  if "*/" in line:
    print line
    break
  elif "/*" in line:
    incomment = True
    print line
  elif incomment:
    print line

To Run:

python code.py <filename>
Brian Gianforcaro
It's cool and it works, but I was really looking for a bash line.
Corey Hart
+3  A: 
$ cat file
one two
// comment.....
/*
 * This is a
 * comment block
 */
# asdgihj
/* adsjf */

$ awk -v RS="*/" -vFS="/[*]" 'NR==1{print "/*"$2RT}' file
/*
 * This is a
 * comment block
 */

$ cat file
/* * comment */
/*
 * This is a
 * comment block
 */
/* adsjf */
$ awk -v RS="*/" -vFS="/[*]" 'NR==1{print "/*"$2RT}' file
/* * comment */

Another way without using gawk RS

$ cat file
dsfsd
/*
 * This is a
 * comment block
 */ sdff
blasdf
/* adsjf */

$ awk '/\/\*/&&/\*\//{print;exit}f&&/\*\//{print "*/";exit}/\/\*/&&!/\*\//{f=1}f' file
/*
 * This is a
 * comment block
*/
ghostdog74
Man, I *really* need to learn some `awk`! I did `sed` then skipped over `awk` to perl.
Vivin Paliath
For some reason if you have a comment like/* * comment */ It add's an extra "*" at the first line. so "/*" comes out as "/**"
Brian Gianforcaro
comment formatting messed up my message
Brian Gianforcaro
Didn't event think about awk. Unfortunately my far behind Mac terminal app doesn't support the -v option. So I can't test what you provided
Corey Hart
@Corey: I think on the Mac a space is required between the `-v` and the variable name.
Dennis Williamson
@Dennis even then, it only grabs the first 2 characters "/*" and not the block.
Corey Hart
@Corey, this is using GNU gawk. If you don't have it, you can try the last version.
ghostdog74
@ghostdog like in your last example, it removes the space on the last line: "*/" should be " */". Sorry, I know your determined on this one.
Corey Hart
+3  A: 
sed -n '/^\/\*/,/^ \*\//p;/^ \*\//q' file

Or equivalently:

sed -n '\|^/\*|,\|^ \*/|p;\|^ \*/|q' file

Edit:

Here is a version of the second one above that handle's the situation mentioned in ghostdog74's comment:

sed -n '\|^/\*.*\*/|{p;q};\|^/\*|,\|^ \*/|p;\|^ \*/|q' file

And if you want to handle whitespace at the beginning and end of lines:

sed -n '\|^[[:space:]]*/\*.*\*/|{p;q};\|^[[:space:]]*/\*|,\|^ \*/|p;\|^[[:space:]]*\*/|q'
Dennis Williamson
Annnnnnd thank you.
Corey Hart
a good one, but that doesn't work 100%. It will give out the multiline comments as well with the 2nd sample file in my answer.
ghostdog74