对于一段文字:
USB2.1 Hub:
Product ID: 0x0610
Dell Universal Dock D6000:
Product ID: 0x6006
Vendor ID: 0x17e9 (DisplayLink (UK) Ltd.)
Version: 31.27
Serial Number: 1810132665
Speed: Up to 5 Gb/s
Manufacturer: DisplayLink
..检测到字符串
DisplayLink
我想返回Dell Universal Dock D6000
(或者具体来说,匹配字段前七行的整行)。
这应该可以用一些
awk
数组:
awk '/DisplayLink/ { for(i=NR-8;i<NR;i++) if(i>0) print a[i]; print; exit} {a[NR}=$0}'
返回语法错误。
使用这个(公认的丑陋,低效的)工具链返回期望的结果:
grep "Manufacturer: DisplayLink" -B7 -n | head -1 | awk -F'[ :]+' '{ $1=""; print $0 }'
假设:
Manufacturer: DisplayLink
调整 OP 的当前代码(将所有行存储在内存中,然后打印行 #
NR-7
):
awk '
/Manufacturer: DisplayLink/ { i=NR-7; if (i>0) print a[i]; exit}
{ a[NR]=$0 }
' dell.dat
仅存储最后 7 行的 OP 代码的替代方案(通过模 7 索引):
awk '
/Manufacturer: DisplayLink/ { i=NR-7; if (i>0) print a[i%7]; exit }
{ a[NR%7] = $0 }
' dell.dat
另一种替代方法需要两次读取输入文件;首先阅读注释我们找到匹配项的行,然后减去 7(称之为
line_no
);第二次读取然后打印 FNR == line_no
: 所在的行
awk 'FNR==NR && /Manufacturer: DisplayLink/ { line_no = FNR-7; nextfile }
FNR==line_no
' dell.dat dell.dat
所有这些产生:
Dell Universal Dock D6000:
tac file |awk '/Manufacturer: DisplayLink/{a=8}{if(--a==0)print}'