I have a test file:
1
2
3
4
5
6
7
8
This command prints the last 4 lines of the file:
$ awk 'BEGIN{"wc -l < file" | getline b}{if(NR>b-4) print}' file
5
6
7
8
userpc@userpc-desktop
Now I want to do the same, but the command system ():
$ awk '{if( NR > (system("wc -l < file")-4) ) print}' file
8
1
8
2
8
3
8
4
8
5
8
6
8
7
8
8
userpc@userpc-desktop:
How to improve the last command system ()? I also want to print 4 last lines of the file.
Thank you for your help.
awkis definitely not the right tool for this. It’s common to do:sed '1{N;N;N;}; N; D; $p', and you can do something similar with awk:Basically, you keep track of the last four lines seen, and print them all when you get to the end of the file. You can be a little more obscure and efficient with:
but, really, why would you?