简体   繁体   English

使用 awk 获取前 n 个匹配项

[英]Get first n matches with awk

I am using dbus-monitor command to see every Dbus signal, the command is an infinite loop, so I am using awk with it to grep for a specific pattern.我正在使用dbus-monitor命令查看每个Dbus信号,该命令是一个无限循环,所以我使用awk来 grep 获取特定模式。

I can get the first match and exit using:我可以使用以下方法获得第一场比赛并退出:

dbus-monitor --system | awk '/<pattern>/ {print $2; exit}'

But, my system is going to a list of states for example x1 -> x2 -> x3但是,我的系统将进入状态列表,例如x1 -> x2 -> x3

I want to use awk to get the first 3 signals of a given pattern and print them.我想使用awk获取给定模式的前 3 个信号并打印它们。

For example, when I start the system, x1 is sent and I can detect it with the first awk command, but when I run it again, I get x3 , because x2 is already sent I did not catch it in time.例如,当我启动系统时,发送了x1并且我可以使用第一个awk命令检测到它,但是当我再次运行它时,我得到了x3 ,因为已经发送了x2我没有及时捕获它。

How can I change awk to use for example a counter and get me the first n matches?如何更改awk以使用例如计数器并让我获得前 n 个匹配项?

Thanks.谢谢。

增加一个计数器变量,然后对其进行测试以决定是否退出。

dbus-monitor --system | awk '/<pattern>/ {counter++; print $2; if (counter == 3) exit}'

you can decrement it down to zero just as easily你可以很容易地把它减到零

jot 1000 | {m,g}awk '__<NF { exit } __>(__-=_^($_ % 181))' FS='^$' __=3
181
362
543

The left side portion handles the exit when counter reaches zero, the right side portion handles the pattern you want it to match, plus keep tracking how many times you've printed so far.当计数器达到零时,左侧部分处理退出,右侧部分处理您希望它匹配的图案,并继续跟踪您到目前为止打印的次数。

here my criteria is simple - find multiples of the prime number 181这里我的标准很简单——找到素数 181 的倍数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM