Linux 在bash中按日期字段对日志进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5242986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort logs by date field in bash
提问by Mejmo
let's have
让我们
126 Mar 8 07:45:09 nod1 /sbin/ccccilio[12712]: INFO: sadasdasdas
2 Mar 9 08:16:22 nod1 /sbin/zzzzo[12712]: sadsdasdas
1 Mar 8 17:20:01 nod1 /usr/sbin/cron[1826]: asdasdas
4 Mar 9 06:24:01 nod1 /USR/SBIN/CRON[27199]: aaaasdsd
1 Mar 9 06:24:01 nod1 /USR/SBIN/CRON[27201]: aaadas
I would like to sort this output by date and time key.
我想按日期和时间键对此输出进行排序。
Thank you very much.
非常感谢。
Martin
马丁
采纳答案by Mejmo
For GNU sort: sort -k2M -k3n -k4
对于 GNU 排序: sort -k2M -k3n -k4
-k2M
sorts by second column by month (this way "March" comes before "April")-k3n
sorts by third column in numeric mode (so that " 9" comes before "10")-k4
sorts by the fourth column.
-k2M
按月按第二列排序(这样“三月”在“四月”之前)-k3n
在数字模式下按第三列排序(以便“9”在“10”之前)-k4
按第四列排序。
See more details in the manual.
查看手册中的更多详细信息。
回答by bmk
You can use the sort command:
您可以使用排序命令:
cat $logfile | sort -M -k 2
That means: Sort by month (-M) beginning from second column (-k 2).
这意味着:从第二列 (-k 2) 开始按月 (-M) 排序。
回答by hias
little off-topic - but anyway. only useful when working within filetrees
有点跑题——但无论如何。仅在文件树中工作时有用
ls -l -r --sort=time
from this you could create a one-liner which for example deletes the oldest backup in town.
由此您可以创建一个单行,例如删除镇上最旧的备份。
ls -l -r --sort=time | grep backup | head -n1 | while read line; do oldbackup=\`echo $line | awk '{print}'\`; rm $oldbackup; done;