me$ cat file.txt
Filename: 1
Organization: Bus 1 => Port 1 => Subport 1 => Device 3
Classes: Interface Video
Drivers: usbhid
Filename: 2
Organization: Bus 1 => Port 1 => Subport 3 => Device 4
Classes: Audio
Drivers: usb-audio uvc Video
Filename: 3
Organization: Bus 1 => Port 1 => Subport 4 => Device 5
Classes: Wireless Video
Drivers: uvc
如何操作此项以返回包含任何给定关键字的块?
例如:bash this --class" Video"会回来:
Filename: 1
Organization: Bus 1 => Port 1 => Subport 1 => Device 3
Classes: Interface Video
Drivers: usbhid
Filename: 3
Organization: Bus 1 => Port 1 => Subport 4 => Device 5
Classes: Wireless Video
Drivers: uvc
编写脚本来对--class和--driver案例进行排序是微不足道的,只是特别询问文本操作。我正在思考grep Class:* $ input,取得行号,并打印从之前的换行到下一行的所有内容,但这样会有更多的复杂性,可能不是最有效的方法。
答案 0 :(得分:1)
获得课程......视频:
$ awk -v RS= '/Classes:[^\n]*Video/' file.txt
Filename: 1
Organization: Bus 1 => Port 1 => Subport 1 => Device 3
Classes: Interface Video
Drivers: usbhid
Filename: 3
Organization: Bus 1 => Port 1 => Subport 4 => Device 5
Classes: Wireless Video
Drivers: uvc
(我用mawk和GNU awk测试了它,它应该适用于任何POSIX awk [帽子提示:ninjalj]但它可能与awk的very old versions不兼容。)
-v RS=
这会将记录分隔符设置为空字符串,通常将其解释为段落。
/Classes:[^\n]*Video/
如果记录(段落)包含Classes:
,后跟除换行符之外的任意数字,后跟Video
,则返回true。换句话说,如果一行包含字符串Classes:
并且稍后包含字符串Video
,则返回true。如果此条件返回true,则awk执行默认操作,即打印记录(段落)。