awk - awk:为什么匹配函数打印匹配的行而不提及打印它
问题描述
我有以下内容:
NODE_1
port 1
description blah
port 2
description blah blah
NODE_2
port 1
description blah
port 2
description blah
NODE_3
port 1
port 2
NODE_4
port 1
port 2
NODE_5
port 1
port 2
NODE_6
port 1
description blahdy blah
port 2
description floop-a-doop
我正在尝试打印 NODE 的前三个匹配项的匹配属性
awk 'BEGIN{count=0}
match($0,/NODE/,a)
{
if(RSTART != 0){
print "*******************************"
for (i in a)
print i"-->"a[i]
count++;
print "count-->"count;
print "*******************************"
}
if (count >= 3)
{
exit
}
}' awksampledata5.txt
输出是
NODE_1
*******************************
0start-->1
0length-->4
0-->NODE
count-->1
*******************************
NODE_2
*******************************
0start-->1
0length-->4
0-->NODE
count-->2
*******************************
NODE_3
*******************************
0start-->1
0length-->4
0-->NODE
count-->3
*******************************
我不想打印 NODE_1、NODE_2 和 NODE_3。但我不知道它是如何被打印出来的。
回答编辑代码:
$ awk 'BEGIN{count=0}
match($0,/NODE/,a){
if(RSTART != 0){ <-- this matters new lines matters.
print "*******************************"
for (i in a)
print i"-->"a[i]
count++;
print "count-->"count;
print "*******************************"
}
if (count >= 3)
{
exit
}
}' awksampledata5.txt
*******************************
0start-->1
0length-->4
0-->NODE
count-->1
*******************************
*******************************
0start-->1
0length-->4
0-->NODE
count-->2
*******************************
*******************************
0start-->1
0length-->4
0-->NODE
count-->3
*******************************
解决方案
换行很重要。这个:
match($0,/foo/)
{ bar() }
与以下任何一个都不相同:
match($0,/foo/) { bar() }
match($0,/foo/) {
bar()
}
第一个脚本说
If "foo" exists in $0 then print the current record.
Call bar().
而另外两个说:
If "foo" exists in $0 then call bar().
推荐阅读
- javascript - 在 Firefox 中通过 AJAX 加载非 XML 数据时出现“XML 解析错误”
- java - 使用 Spring 反序列化请求时如何处理动态 JSON 值类型?
- python - 为什么我会收到错误“NameError: name 'kh' is not defined”
- c - c语言中的JOIN函数,valgrind问题
- git - SmartGit 提交地址
- unity3d - 为什么只有在相机靠近时才能听到此音频源?
- c - 如何获取每行中的字符数?
- gradle - 覆盖 gradle 子项目中的存储库定义
- c++ - 相邻差异与 pre 和 next 一起使用
- javascript - 如果工作表 1 中的复选框为真,请删除工作表 2 Google 电子表格中具有相同值的行