当前位置:首页 > 操作系统 > Linux

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

我从几个不同的日志文件中得到了输出:

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

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

更新:
这是输出的来源

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

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐