Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using awk script to print last n rows of a text file

Tags:

awk

I need a script to print last n rows of a text file. the text file names and number of rows can be varied and I want to call only script to print last n rows of any text files. I know for first n row I can use NR < n; print but how can I do it for last n row as number of rows can be varied.- thanks

like image 528
Sajjad Avatar asked Dec 05 '25 14:12

Sajjad


2 Answers

There is a unix tool for exactly that purpose, called tail. To get the last 100 rows of file, you would use tail -n 100 file, then use the output directly or pipe it to other programs like awk.

like image 193
Lars Fischer Avatar answered Dec 08 '25 05:12

Lars Fischer


To do this natively in awk, you have to remember the lines as you see them:

awk -v n=10 '
    {line[NR]=$0}
    END {for (i=NR-(n-1); i<=NR; i++) print line[i]}
' file

To save memory, we don't need to remember the whole file; use

    {line[NR]=$0; if (NR>n) delete line[NR-n]}

However it is simpler to reverse the file, print the first n lines, and re-reverse the output

tac file | awk -v n=10 'NR <= n' | tac

But using tail is much simpler that all that

like image 36
glenn jackman Avatar answered Dec 08 '25 07:12

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!