linux - 如何按日期对多个日志文件的输出进行排序

标签 linux bash sed awk

我有几个不同日志文件的输出:

logfile3
2010/07/21 15:28:52 INFO xxx
2010/07/21 15:31:25 INFO xxx
2010/07/21 15:31:25 DEBUG xxx

logfile1
2010/07/21 19:28:52 INFO xxx
2010/07/21 19:31:25 INFO xxx
2010/07/21 19:31:25 DEBUG xxx

logfile2
2010/07/21 13:28:52 INFO xxx
2010/07/21 13:31:25 INFO xxx
2010/07/21 13:31:25 DEBUG xxx

我想按日期对输出进行排序,但将日志文件的名称保留在日志行上方,因此它应该如下所示:

logfile2
2010/07/21 13:28:52 INFO xxx
2010/07/21 13:31:25 INFO xxx
2010/07/21 13:31:25 DEBUG xxx

logfile3
2010/07/21 15:28:52 INFO xxx
2010/07/21 15:31:25 INFO xxx
2010/07/21 15:31:25 DEBUG xxx

logfile1
2010/07/21 19:28:52 INFO xxx
2010/07/21 19:31:25 INFO xxx
2010/07/21 19:31:25 DEBUG xxx

您知道如何使用 bash 命令、sed 或 awk 对这样的输出进行排序吗? 非常感谢!

更新: 这是输出的来源

for i in $( find log/ -iname *debug*.log -size +0 );do
if [ `grep -c 'ERROR' $i` -gt 0 ];then
 echo -e "\n$i"
 grep 'ERROR' --color=auto -A 5 -B 5 $i
fi
done

马丁

最佳答案

你可能会从中得到满意的结果(只要你的文件名不包含冒号):

grep -C 5 --recursive 'ERROR' log/* | sort --field-separator=: --key=2

每一行都将以文件名作为前缀。您的输出将如下所示:

logfile2:2010/07/21 13:28:52 INFO xxx
logfile2:2010/07/21 13:31:25 INFO xxx
logfile2:2010/07/21 13:31:25 DEBUG xxx

logfile3:2010/07/21 15:28:52 INFO xxx
logfile3:2010/07/21 15:31:25 INFO xxx
logfile3:2010/07/21 15:31:25 DEBUG xxx
etc.

您可以使用 AWK 将其重新格式化为您在示例中显示的格式:

grep -C 5 --recursive 'ERROR' log/* | sort --field-separator=: --key=2 |
    awk '{colon = match($0,":"); file = substr($0,1,colon - 1); 
    if (file != prevfile) {print "\n" file; prevfile = file}; 
    print substr($0,colon+1)}'

以下是对您的脚本的一些改进,以防您仍然使用它:

find log/ -iname "*debug*.log" -size +0 | while read -r file
do
    if grep -qsm 1 'ERROR' "$file"
    then
        echo -e "\n$file"
        grep 'ERROR' --color=auto -C 5 "$file"
    fi
done

关于linux - 如何按日期对多个日志文件的输出进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3302900/

相关文章:

linux - 如何将 cuDNN 更新到新版本?

linux - 相当于 head/tail 命令显示头/尾或一行

linux - Shell 脚本 - 将 sed 与具有/的变量一起使用

Bash 脚本 : Gzip an entire folder and keep files extensions same

Linux脚本更改文件名、文件夹名和成分

linux - 如何在 unix shell 中转置行和列?

php - 如何解码 unicode python 参数?

linux - 在 Linux 上移动 Git 安装

c - 在 Linux 中创建套接字时是否有任何错误日志文件显示内核错误?

bash - 如何使用 curl 和 dpkg 在一行中获取和安装