When learning to use awk
, I found the expression awk 'c&&!--c;/regex/{c=N}'
as a way to select and print the N
th line below the line matching the regex. I understand that c
is initially equal to 0
so the first match isn't printed but despite having searched high and low, I don't know how to interpret the remaining syntax (outside of the /regex/
) and how it specifically knows to count N
lines before printing.
Can someone explain what c&&!--c
means and how it works as a counter with the rest of the function?
The first half of the expression c
will evaluate to true
if c != 0
as you correctly guessed.
The second half of the expression !--c
will evaluate to true
if --c
evaluates to 0
; this happens when c==1
immediately beforehand. Moreover, the expression will always decrement c
as long as c != 0
, so c
can serve as a line counter.
When the regular expression matches, we set c == N
so that after exactly N
lines (each one decrements c
by 1), c==1
, and awk
will print the line.