LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Maximum Date Value from a file (https://www.linuxquestions.org/questions/linux-newbie-8/maximum-date-value-from-a-file-879905/)

Sourav_Das 05-10-2011 04:02 PM

Maximum Date Value from a file
 
Hi ..

I am facing a problem in finding out the maximum value of a field using awk .. The field is of date format i.e. (MM/DD/YYYY) ..

The contents of the file is :

2/2/2011 XYZ
2/2/2011 XYZ1
2/3/2011 ABC
2/4/2011 ABC
.
.
.
2/9/2011 XYZ
2/10/2011 XYZ
2/11/2011 XYZ
2/12/2011 XYZ

I need to find the maximum of the first column i.e. my output should be 2/12/2011 ..

I was using the below awk script :
awk 'n < $0 {n=$0} {print n}{print $0}' <source_file having the above data>

But the output I am getting is 2/9/2011 instead of 2/12/2011 ...

Can anyone please tell me as what could be reason for this output and how can I get my desired result ..?

Regards,
Sourav

SL00b 05-10-2011 04:08 PM

Alignment.

One method to resolve this would be to re-format your date fields so they're padded with left zeroes, like so:

02/02/2011 XYZ
02/02/2011 XYZ1
02/03/2011 ABC
02/04/2011 ABC
...
02/09/2011 XYZ
02/10/2011 XYZ
02/11/2011 XYZ
02/12/2011 XYZ

And you should be good to go.

If you're not padding left zeroes, you're not truly in MM/DD/YYYY format.

The next option would be beyond my skill set... you'd have to figure out how to use the / character as a delimiter.

Tinkster 05-10-2011 06:00 PM

Just a word of caution; this will only work if there's always ever only
ONE months worth of dates from the SAME year in the file:
Code:

awk -F"[/ ]" 'BEGIN{oldd=""}{if(oldd<$2){p=$0;oldd=$2}}END{print p}' sourav
2/12/2011 XYZ



Cheers,
Tink

Sourav_Das 05-23-2011 10:09 PM

Thanks for your replies ... Sorry for the delay in replying ...

To SL00b,
I finally thought of going to the route u suggested by having all the dates in format MM/DD/YYYY , it was working fine till I encountered the below dates in the file

12/31/2010
01/01/2011

I was expecting an O/P 01/01/2011 but the script gave 12/31/2010.. Can anyone please help?


All times are GMT -5. The time now is 02:50 PM.