[英]a command executed when pattern rule is not true in awk, what's wrong?
再次出现一个奇怪的awk现象..(这一直在发生:))
我在下面有一个文件aaa。
[first]
aaa
bbb
[second]
ccc
ddd
eee
[third]
fff
ggg
hhh
iii
我正在尝试打印每个部分的行号,该行号以包含在括号中的标题开头。 因此,我在下面编写了一个简单的awk脚本CntSecLines.awk(正在调试,因此带有一些打印件)。
/\[/{print "header found : "; print $keep " : " cnt; keep=$1; cnt=0}
!/\[/{print "header not found"; cnt = cnt+1; print "keep = " $keep;}
以下是aaa的执行结果。
ckim@stph45:~/test] awk -f CntSecLines.awk aaa
header found :
[first] :
header not found
keep = aaa
header not found
keep = bbb
header found :
[second] : 2
header not found
keep = ccc
header not found
keep = ddd
header not found
keep = eee
header found :
[third] : 3
header not found
keep = fff
header not found
keep = ggg
header not found
keep = hhh
header not found
keep = iii
我打算仅在有节标题时才对其进行更新。 但是为什么变量“ keep”每行都会更新? 当我打印变量$ keep时,我们可以看到它正在每条非节头行中进行更新。
awk
,不是bash
。 在awk
您不使用$
来获取变量值(当然,有例外,例如位置参数$1
, $2
...)。
awk '
/\[/{print "header found : "; print keep " : " cnt; keep=$1; cnt=0}
!/\[/{print "header not found"; cnt = cnt+1; print "keep = " keep;}
' <<EOF
[first]
aaa
bbb
[second]
ccc
ddd
eee
[third]
fff
ggg
hhh
iii
EOF
将输出:
header found :
:
header not found
keep = [first]
header not found
keep = [first]
header found :
[first] : 2
header not found
keep = [second]
header not found
keep = [second]
header not found
keep = [second]
header found :
[second] : 3
header not found
keep = [third]
header not found
keep = [third]
header not found
keep = [third]
header not found
keep = [third]
经repl测试。
我相信awk
会将$keep
解释为像$
的字符串[blabla]
,例如$"[blabla]"
,然后将"[blabla]"
从字符串转换为数字,结果为0
,因此$keep
是解释为$0
,将打印整行。
我将您的要求解释为“计算每个用括号分隔的部分中的行数”。
$ awk '/^\[.*\]$/ {c=0; print; next} {print ++c, $0}' file
[first]
1 aaa
2 bbb
[second]
1 ccc
2 ddd
3 eee
[third]
1 fff
2 ggg
3 hhh
4 iii
/^\\[.*\\]$/
如果记录以文字[
开始,以文字]
结尾
{c=0; print; next}
{c=0; print; next}
-设置/重置计数,打印记录,跳过剩余规则
{print ++c, $0}
对于不匹配的第一个规则记录,打印预递增计数时,输出字段分隔符,
和记录$0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.