Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort logs by date field in bash

People also ask

How do I sort a column by date in Linux?

The option -k 2,2n -k 3 sorts each column. First, it will sort 2nd column (date dd field) and then 3rd column (time). data. file.

How do I order ls by date?

In order to ls by date or list Unix files in last modifed date order use the -t flag which is for 'time last modified'. or to ls by date in reverse date order use the -t flag as before but this time with the -r flag which is for 'reverse'.

How do I sort a column in bash?

Sort Command Options You can use the following options in conjunction with the raw command to modify how the values are sorted. -n – sorts in numerical values. -R – sort in random order but group the identical keys. -r – sort the values in reverse (descending order).

What is $s in bash?

From man bash : -s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell.


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).