使用 awk 筛选最后 100 行的日志



我可以使用 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
}'

你能试试下面的吗?

tac Input_file | awk 'FNR<=100 && /error/' | tac

如果您想在命令中添加行数awk请尝试以下操作。

awk '/ERROR/{print FNR,$0}' Input_file

相关内容