我有几个不同日志文件的输出:
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/