开发者

Bash script to pull out x number of starting comment lines into another file

开发者 https://www.devze.com 2022-12-27 00:06 出处:网络
I am looking for a one liner to pull out the first comment block in any file. The comment blocks look like this:

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

/*
 * T开发者_Go百科his is a 
 * comment block
 */

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


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'


$ 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
*/


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消