如何扩展不在注释中的模式的值(另一个模式)

时间:2019-06-30 15:22:36

标签: shell sed

仅从非注释部分中提取“ 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

2 个答案:

答案 0 :(得分:1)

这似乎可行:

sed -n -e:a -e'/\*\//d;/\/\*/{N;ba
};s/^var=//p'

最简单的部分是从行中提取值;困难的部分是先删除评论。粗略翻译:如果有*/,则删除所有内容;否则,如果有/*,则还要阅读下一行并重新开始;否则,请重新开始。否则,如果该行以“ var =“开头,则删除该部分并打印其余部分。

注意1:您的sed版本可能不需要烦人的换行符。
注意2:建议您在脚本中尝试使用此命令之前,先在命令行上进行测试。

答案 1 :(得分:0)

这是一种删除注释的廉价而愉快的方法,正如您在多字符RS中使用GNU awk所显示的那样:

$ 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的值。如果这还不是您所需要的,那么请获取/使用解析器来编写注释代码所用的任何语言,例如有关C / C ++,请参见https://stackoverflow.com/a/13062682/1745001