sed -n 's/\(.*user: \)\([^ ]*\)$/\2 \1\2/p' <<\DATA |\
sort -t' ' -k1,1 -k2,3M |\
sed 's/[^ ]* //'
Feb 7 domainserver dovecot[37495]: auth(default): od(tjones): lookup failed for user: tjones
Feb 8 domainserver dovecot[37495]: auth(default): od(tjones): lookup failed for user: tjones
Feb 5 domainserver dovecot[37495]: auth(default): od(lbones): lookup failed for user: lbones
Jan 7 domainserver dovecot[37495]: auth(default): od(chaz): lookup failed for user: chaz
Mar 7 domainserver dovecot[37495]: auth(default): od(lbones): lookup failed for user: lbones
DATA
OUTPUT
Jan 7 domainserver dovecot[37495]: auth(default): od(chaz): lookup failed for user: chaz
Feb 5 domainserver dovecot[37495]: auth(default): od(lbones): lookup failed for user: lbones
Mar 7 domainserver dovecot[37495]: auth(default): od(lbones): lookup failed for user: lbones
Feb 7 domainserver dovecot[37495]: auth(default): od(tjones): lookup failed for user: tjones
Feb 8 domainserver dovecot[37495]: auth(default): od(tjones): lookup failed for user: tjones
This prunes the data first, by only selecting lines that contain the string user: and copying the following field to the head of the line. So, given the following data:
*CRUFT*user: nospaces$
Where $
represents the end of the line, the first thing sed
does is:
nospaces *CRUFT*user: nospaces$
...copy nospaces to the head of the line. This is a common practice in these sorts of operations, because often even a variation of 1 or 2 in the number of fields in any of the lines can drastically affect the sort
. It is far better to copy the important fields to the start of the line in order to sort
only on those. In any case, that is what occurs here.
So sed
passes its edited data over the |pipe
to sort
, which sorts first on the first field - the username - and next by MONTH
on a -k
ey combining both the second and third fields. The result is all lines are grouped by username and each grouping is sorted by date.
Last sort
hands its data back to sed
over another |pipe
and sed
strips the first field of the line - which is only there because it copied it there in the first place.