Home > Blockchain >  Get first n matches with awk
Get first n matches with awk

Time:07-21

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.

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

I want to use awk to get the first 3 signals of a given pattern and print them.

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.

How can I change awk to use for example a counter and get me the first n matches?

Thanks.

CodePudding user response:

Increment a counter variable, then test it to decide whether to exit.

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

CodePudding user response:

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

  • Related