Implement tail with awk

后端 未结 4 1557
失恋的感觉
失恋的感觉 2021-01-19 16:44

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++)
            


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 17:40

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

    $ indicates a positional parameter. Use just plain i:

    for(i=NR-num;i<=NR;i++)
        print vect[i]
    

    The full code that worked for me is:

    #!/usr/bin/awk -f
    BEGIN{
            num=ARGV[1];
            # Make that arg empty so awk doesn't interpret it as a file name.
            ARGV[1] = "";
    }
    {
            vect[NR]=$0;
    }
    END{
            for(i=NR-num;i<=NR;i++)
                    print vect[i]
    }
    

    You should probably add some code to the END to handle the case when NR < num.

提交回复
热议问题