提取" value ="仅来自非关注部分
请参阅下面的SED表达式,该表达式从评论代码中获得价值
我尝试了GREP,但这也行不通
#!/bin/sh
#set -x
FILE="/tmp/comment.txt"
create_file () {
echo "/*" > $FILE
echo "this is a multi" >> $FILE
echo "line with" >> $FILE
echo "var=20" >> $FILE
echo "and ending the comment */" >> $FILE
echo "var=15" >> $FILE # line after comment
}
create_file
cat $FILE
# This sed should extract only from var=15 which is not part of
# comments, how to do that?
# output should be only 15, instead of "20 and 15"
sed -n "s/(var=)([0-9]*)/2/p" $FILE
实际:
/*
this is a multi
line with
var=20
and ending the comment */
var=15
20
15
预期:
/*
this is a multi
line with
var=20
and ending the comment */
var=15
15
这似乎有效:
sed -n -e:a -e'/*//d;//*/{N;ba
};s/^var=//p'
简单的部分是从线上提取值。困难的部分是首先删除评论。粗略翻译:如果有*/
,则删除所有内容;否则,如果有 /*
,则也要读取下一行并重新开始;否则,如果行开头是" var =",则删除该零件并打印其余部分。
注意1:在您的SED版本中可能不需要烦人的线路。
注2:我建议您在命令行上进行测试,然后在脚本中尝试。
这是您使用GNU AWK进行多char rs显示的廉价而开朗的评论的方式:
$ awk -v RS='[*]/' -v ORS= '{sub("/[*].*","")}1' file
var=15
无论他们在何处/在每行停止何处,都会剥离评论:
$ cat file
here's some text /* here's a comment */ and more text /* bleh */and more /*
this is a multi
line with
ending here */ and more
var=20/*
and ending the comment */
/* commented */ var=15
$ awk -v RS='[*]/' -v ORS= '{sub("/[*].*","")} 1' file
here's some text and more text and more and more
var=20
var=15
它只是无法识别出看起来像评论的字符串开始/在字符串或其他特定于语言的构造中。
您可以将其送至您喜欢获得var
值的任何东西。如果这不是您所需要的,那么请获取/使用解析器,以使用您的评论代码写的任何语言,例如请参阅https://stackoverflow.com/a/13062682/1745001有关C/C 。