2009-07-17 238 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