Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print last 10 rows of specific columns using awk

Tags:

bash

awk

I have the below awk command-line argument and it works aside from the fact it performs the print argument on the entire file (as expected). I would like it to just perform the formatting on the last 10 lines of the file (or any arbitrary number). Any suggestions are greatly appreciated, thanks!

I know one solution would be to pipe it with tail, but would like to stick with a pure awk solution.

awk '{print "<category label=\"" $13 " " $14 " " $15 "\"/>"}' foofile
like image 482
jparanich Avatar asked Dec 19 '25 02:12

jparanich


2 Answers

There is no need to be orthodox with a language or tool on the Unix shell.

tail -10 foofile | awk '{print "<category label=\"" $13 " " $14 " " $15 "\"/>"}'

is a good solution. And, you already had it.

Your arbitrary number can still be used as an argument to tail, nothing is lost;
solution does not lose any elegance.

like image 194
nik Avatar answered Dec 20 '25 17:12

nik


Using ring buffers, this one-liner prints last 10 lines;

awk '{a[NR%10]=$0}END{for(i=NR+1;i<=NR+10;i++)print a[i%10]}'

then, you can merge "print last 10 lines" and "print specific columns" like below;

{
    arr_line[NR % 10] = $0;
}

END {
    for (i = NR + 1; i <= NR + 10; i++) {
        split(arr_line[i % 10], arr_field);
        print "<category label=\"" arr_field[13] " " \
                                   arr_field[14] " " \
                                   arr_field[15] "\"/>";
    }
}
like image 21
Hirofumi Saito Avatar answered Dec 20 '25 16:12

Hirofumi Saito