I have data like this:
Code Date(YYYYDDMM)
VNM 20141202
VNM 20141203
VNM 20141204
BHR 20141203
BHR 20141204
RUS 20150312
RUS 20142312
Now I want to select the VNM
which is having latest date using UNIX command.
How I can do that?
I would use awk
to convert the dates into timestamp, then compare them with sort
and finally print the first column from the biggest one:
awk 'NR>1{y=substr($2,0,4)
d=substr($2,5,2)
m=substr($2,7,2)
date=sprintf("%d %d %d 0 0 0",y,m,d)
print $1, mktime(date)}' a |\
sort -k2 -n |\
awk 'END {print $1}'
Note the current dates are in the YYYYDDMM format, that's why I have to reverse them to call mktime
.
$ awk 'NR>1{y=substr($2,0,4); d=substr($2,5,2); m=substr($2,7,2); date=sprintf("%d %d %d 0 0 0",y,m,d); print $1, mktime(date)}' a
VNM 1392159600
VNM 1394578800
VNM 1397253600
BHR 1394578800
BHR 1397253600
RUS 1449097200
RUS 1419289200
$ awk 'NR>1{y=substr($2,0,4); d=substr($2,5,2); m=substr($2,7,2); date=sprintf("%d %d %d 0 0 0",y,m,d); print $1, mktime(date)}' a | sort -k2 -n
VNM 1392159600
BHR 1394578800
VNM 1394578800
BHR 1397253600
VNM 1397253600
RUS 1419289200
RUS 1449097200
$ awk 'NR>1{y=substr($2,0,4); d=substr($2,5,2); m=substr($2,7,2); date=sprintf("%d %d %d 0 0 0",y,m,d); print $1, mktime(date)}' a | sort -k2 -n | awk 'END {print $1}'
RUS