1

I've been using

awk '/KEYWORD/{print $0}' FILENAME

to filter a file, how do I modify the command so as to print the last n lines only?

Carlos
  • 19
  • 4
  • 2
    Use `tail` on the output – Sundeep Nov 11 '21 at 07:42
  • 1
    `awk '/KEYWORD/{print $0}' FILENAME | tail -n n` where `-n` is the option for number of ending rows to output and `n` is you `n` number. – David C. Rankin Nov 11 '21 at 08:03
  • 1
    `awk '/KEYWORD/ { print $0 }'` does the same thing as `grep`, so `grep KEYWORD | tail -n $n` would be enough – Thor Nov 11 '21 at 08:08
  • 1
    This can help you: https://stackoverflow.com/questions/36390128/using-awk-script-to-print-last-n-rows-of-a-text-file – Carlos Pascual Nov 11 '21 at 08:20
  • @Carlos : depends on how big the post-filter size is. If it's `< 1 GB` or so, just use 1 `awk` to filter and pipe to 1 more `awk`, this time set `RS = "^$"; FS = "\n"`, jump to the `END { }` section, figure out which field is the N-th last one (keeping in mind that `NF` is 1 more than # of `\n`). If that field (row)'s contents never existed b4, then simply `substr()` from there till the end. Otherwise, I'd prefix that field w/ a custom sep of whacko byte combos, eg `"\371\17\301"`. use `sub()` to clean off everything to left of it, inc the sep, then print the rest. Default to `tail` or array. – RARE Kpop Manifesto Jun 25 '23 at 16:07

1 Answers1

0

To do this in awk only, without additional filtering through tail or whatever, we can build an N element FIFO buffer into which we put all the matches. Then we just dump the relevant content from the buffer when done.

BEGIN { N = 10; i = 0 }

/keyword/ { fifo[i] = $0; i = (i + 1) % N }

END { for (x = -N; x < 0; x++)
      { j = (i + x + N) % N
        if (fifo[j])
           print fifo[j] } }
Kaz
  • 55,781
  • 9
  • 100
  • 149