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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With