0

How can I print the last three dates of the next output:

User;month/day/year

    user1:01/01/2015
    user1:01/01/2015
    user1:01/01/2015
    ...
    user1:01/09/2018
    user1:01/08/2018
    user1:01/07/2018
    user1:01/04/2016
    user1:01/02/2016
    user1:01/01/2016

In this case (the 2018 dates)

EDIT:

I have the next command with awk:

awk '{ print $1":" substr( $0,285,291 )}' $file_input | awk '{ print $1}' | sort -n -r

Desired Output:

    user1:01/09/2018
    user1:01/08/2018
    user1:01/07/2018
  • Is that mm/dd/YYYY (USA) or dd/mm/YYYY? I'd recommend using YYYY-mm-dd which is unambiguous and easier to sort. – Stéphane Chazelas Sep 3 '18 at 16:43
  • Oh my fault, my file input has USA dates (mm/dd/YYYY). Is there another way to sort it without change the format? – Mareyes Sep 3 '18 at 16:46
  • Related - unix.stackexchange.com/questions/86413/…. – slm Sep 3 '18 at 18:40
2

Here, sort on the YYYY part and then on the mm/dd part lexically.

That would be the 7th to 10th characters and 1st to 5th of the second :-delimited field respectively, so:

<file sort -r -b -t: -k2.7,2.10 -k 2.1,2.5 | head -n 3

(here adding a -b to allow (and ignore) blanks around the :)

1

Consider using sort like this:

sort -rt/ -k3n -k1.11n -k2n < input | head -3

This sorts the lines based on 3 key fields, based on a / delimiter: first the year, then the month (field 1, skipping past the username and colon), then field 2 -- all numerically sorted. The tail -3 outputs only the last (latest) 3 lines/dates.

  • 4
    Or sort -rbt: -k2.7,2.10 -k2.1,2.5 | head -n3 – Stéphane Chazelas Sep 3 '18 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.