2

When learning to use awk, I found the expression awk 'c&&!--c;/regex/{c=N}' as a way to select and print the Nth 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?

wclose
  • 23
  • 3

1 Answers1

3

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.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Awesome, this actually helps a lot. Does that mean that there is a hidden `{print}` command at the end of the expression as part of `awk`s default behavior? – wclose May 11 '18 at 17:13