2009-07-17 46 views
2

我有下面的awk命令行参数,它除了在整个文件上执行print参数的事实(如预期的那样)。我希望它只是在文件的最后10行(或任意数字)上执行格式化。任何建议,非常感谢,谢谢!使用awk打印最后10行的特定列

我知道一个解决方案就是用尾巴管道,但想坚持一个纯粹的awk解决方案。

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

回答

9

没有必要是与正统的Unix外壳语言或工具。

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

一个很好的解决方案。而且,你已经拥有了它。

你的任意数字仍然可以作为尾部参数使用,没有任何东西丢失;
解决方案不会失去任何优雅。

+1

+1对于Unix哲学 - 正交小工具,做好自己的事情好。 – Eclipse 2009-07-17 15:05:22

0

有AWK的载荷一个衬里,不知道是否有这些将帮助。

具体地说,这可能是你以后在做什么(类似的东西反正):

# print the last 2 lines of a file (emulates "tail -2") 
awk '{y=x "\n" $0; x=$0};END{print y}' 
0
awk '{ y=x "\n" $0; x=$0 }; END { print y }' 

这是非常低效的:它是逐行读取整个文件行什么只打印最后两条线。
由于awk中没有seek()语句,建议使用尾部来打印文件的最后一行。

2

我不认为这可以在awk中完成。唯一的办法是缓冲最后的X行,然后将它们打印在END块中。

我想你会更好用尾巴翘:-)

1

只为最后10行

awk 'BEGIN{OFS="\n"} 
{ 
    a=b;b=c;c=d;d=e;e=f;f=g;g=h;h=i;i=j;j=$0 
}END{  
    print a,b,c,d,e,f,g,h,i,j 
}' file 
3

使用环形缓冲器,该单行打印最后10行;

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

然后,你可以合并“print last 10 lines”和“print specific columns”like like;

{ 
    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] "\"/>"; 
    } 
} 
1

在列变量#的情况下,我已经制定了两种解决方案

#cutlast [number] [[$1] [$2] [$3]...] 

function cutlast { 
    length=${1-1}; shift 
    list=(${@-`cat /proc/${$}/fd/0`}) 
    output=${list[@]:${#list[@]}-${length-1}} 
    test -z "$output" && exit 1 || echo $output && exit 0 
} 
#example: cutlast 2 one two three print print # echo`s print print 
#example1: echo one two three four print print | cutlast 2 # echo`s print print 

function cutlast { 
    length=${1-1}; shift 
    list=(${@-`cat /proc/${$}/fd/0`}) 
    aoutput=${@-`cat /proc/${$}/fd/0`} | rev | cut -d ' ' -f-$num | rev 
    test -z "$output" && exit 1 || echo $output && exit 0 
} 

#example: cutlast 2 one two three print print # echo`s print print