[英]Print last 10 rows of specific columns using awk
我有下面的awk命令行參數,除了它在整個文件上執行print參數(正如預期)這樣做之外。 我希望它只是在文件的最后10行(或任意數字)上執行格式化。 非常感謝任何建議,謝謝!
我知道一個解決方案是用尾巴管道,但是想堅持使用純awk解決方案。
awk '{print "<category label=\"" $13 " " $14 " " $15 "\"/>"}' foofile
在Unix shell上沒有必要使用語言或工具。
tail -10 foofile | awk '{print "<category label=\"" $13 " " $14 " " $15 "\"/>"}'
是一個很好的解決方案 而且,你已經擁有它了。
你的任意數字仍然可以作為尾巴的參數,沒有任何東西丟失;
解決方案不會失去任何優雅。
使用環形緩沖器,這個單線程打印最后10行;
awk '{a[NR%10]=$0}END{for(i=NR+1;i<=NR+10;i++)print a[i%10]}'
然后,您可以合並“打印最后10行”和“打印特定列”,如下所示;
{
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] "\"/>";
}
}
我不認為這可以在awk中整齊地完成。 你能做到的唯一方法是緩沖最后的X行,然后在END塊中打印它們。
我覺得你最好堅持使用尾巴:-)
僅為最后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
在變量#列的情況下,我已經找到了兩個解決方案
#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
本文檔中有大量的awk一個襯墊,不確定是否有任何幫助。
這可能就是你所追求的(無論如何都是類似的):
# print the last 2 lines of a file (emulates "tail -2")
awk '{y=x "\n" $0; x=$0};END{print y}'
awk '{ y=x "\n" $0; x=$0 }; END { print y }'
這是非常低效的:它的作用是逐行讀取整個文件以打印最后兩行。
因為awk中沒有seek()語句,所以建議使用tail來打印文件的最后幾行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.