【发布时间】:2019-01-02 13:42:36
【问题描述】:
我可以使用 tail 或 grep 过滤最后 500 行
tail --line 500 my_log | grep "ERROR"
使用awk的等效命令是什么
如何在下面的命令中添加行数
awk '/ERROR/' my_log
【问题讨论】:
我可以使用 tail 或 grep 过滤最后 500 行
tail --line 500 my_log | grep "ERROR"
使用awk的等效命令是什么
如何在下面的命令中添加行数
awk '/ERROR/' my_log
【问题讨论】:
awk 在读取文件更改之前不知道文件的结尾,但是您可以读取两次文件,第一次找到结尾,第二次处理范围内的行。您也可以将 X 最后一行保留在缓冲区中,但它在内存消耗和处理方面有点繁重。请注意,该文件需要在最后提及两次。
awk 'FNR==NR{L=NR-500;next};FNR>=L && /ERROR/{ print FNR":"$0}' my_log my_log
有解释
awk '# first reading
FNR==NR{
#last line is this minus 500
LL=NR-500
# go to next line (for this file)
next
}
# at second read (due to previous section filtering)
# if line number is after(included) LL AND error is on the line content, print it
FNR >= LL && /ERROR/ { print FNR ":" $0 }
' my_log my_log
在 gnu sed 上
sed '$-500,$ {/ERROR/ p}' my_log
【讨论】:
由于您没有要测试的样本数据,我将使用seq 1 10 仅显示数字。这个存储最后的n记录并在最后打印出来:
$ seq 1 10 |
awk -v n=3 '{a[++c]=$0;delete a[c-n]}END{for(i=c-n+1;i<=c;i++)print a[i]}'
8
9
10
如果您想过滤数据,请在{a[++c]=$0; ... 之前添加例如/ERROR/。
解释:
awk -v n=3 '{ # set wanted amount of records
a[++c]=$0 # hash to a
delete a[c-n] # delete the ones outside of the window
}
END { # in the end
for(i=c-n+1;i<=c;i++) # in order
print a[i] # output records
}'
【讨论】:
a[NR%n]=$0可能会更方便,然后for(i=NR+1;i<=NR+n;i++) if (a[i%n] ~ /ERROR/) print a[i%n]不知道会不会更快(delete vs %)
请您尝试关注一下。
tac Input_file | awk 'FNR<=100 && /error/' | tac
如果您想在awk 命令中添加行数,请尝试以下操作。
awk '/ERROR/{print FNR,$0}' Input_file
【讨论】: