[英]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.