Stephen Ostermiller
Stephen Ostermiller

Reputation: 25524

In bash how do I print the first C style comment from a file

I'm looking for a bash one-liner to print the comment at the top of source files that contains the copyright information. Calling the command on these examples should produce the described output.

/*
 * copyright 2004
 */
package Foo
...

Should print the first three lines

/* copyright 2004 */
package Foo
...

Should print the first line

package Foo
/* some other comment */
...

Should print nothing

I think it should be fairly easy to do in perl or awk, but I can't seem to get it to work.

Upvotes: 2

Views: 349

Answers (1)

user000001
user000001

Reputation: 33327

This awk command seems to work with the given input, but it is probably not reliable enough for general use:

awk 'NR==1&&/^\/\*/{s=1}s==1{print $0}s==1&&$NF=="*/"{s=0}' test.c

In order for it to print the output, the first line should start with /*, and it will print all lines until it reaches a line that ends with */.

Update: In order to work with whitespaces before the /* and with blank lines in the beginning of the file, we can use this command.

 awk 'NF==0&&s==0{NR=0}NR==1&&$1=="/*"{s=1}s==1{print $0}$NF=="*/"{s=2}' test.c

Upvotes: 2

Related Questions