开发者

Sort logs by date field in bash

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]:开发者_如何学JAVA 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


For GNU sort: 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.

See more details in the manual.


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$8}'\`; rm $oldbackup; done;


days need numeric (not lexical) sort, so it should be sort -s -k 2M -k 3n -k 4,4

See more details here.


You can use the sort command:

cat $logfile | sort -M -k 2

That means: Sort by month (-M) beginning from second column (-k 2).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜