Implement tail with awk

Question!

Alright so here i am struggling with this awk code wich should emulate the tail command

num=$1;
{
    vect[NR]=$0;

}
END{
    for(i=NR-num;i<=NR;i++)
            print vect[$i]
}

So what i'm trying to achieve here is an tail command emulated by awk for example consider cat somefile | awk -f tail.awk 10 shoud print the last 10 lines of a text file,any suggestions ?



Answers

You need to add -v num=10 to the awk commandline to set the value of num. And start at NR-num 1 in your final loop, otherwise you'll end up with num 1 lines of output.



This might work for you:

awk '{a=a b $0;b=RS;if(NR
By : potong


All of these answers store the entire source file. That's a horrible idea and will break on larger files.

Here's a quick way to store only the number of lines to be outputted (note that the more efficient tail will always be faster because it doesn't read the entire source file!):

awk -vt=10 '{o[NR%t]=$0}END{i=(NR
By : Adam Katz


This video can help you solving your question :)
By: admin