Fetch the latest filename shell script

Hi

I want to fetch the latest file form the list
example

example= filename RATE_STATE_SETUPS.20151222.ccyymmdd.hhmmss.txt
File pick which have latest ccyymmdd.hhmmss

list of file in directory are

RATE_STATE_SETUPS.20151222.20151222.170101.txt
RATE_STATE_SETUPS.20151222.20151222.140101.txt
RATE_MEDD_SETUPS.20151222.20151222.150102.txt   RATE_MEDD_SETUPS.20151222.20151222.081212.txt
RATE_MEDD_SETUPS.20151222.20151222.121212.txt

I want that code return two latest file

RATE_STATE_SETUPS.20151222.20151222.170101.txt
RATE_MEDD_SETUPS.20151222.20151222.150102.txt
ls | awk -F "." '{ OFS=".";print $3,$4 }' | sort -n -k 2,2 | tail -1

My code return only one file

RATE_STATE_SETUPS.20151222.20151222.170101.txt

My OS is AIX 6
Thanks in advance

tail -1 will only display the last one. tail -2 will display last two.

Thanks in advance
tail -2 return two file but I have to handle the film type there is two type in example STATE AND MEdd I want that code return one from state type and another from medd type on the basis of latest timestamp

You could try:

EDIT: I did misunderstand, fixing now
Fixed, note sure if I got it right, though.

ls|awk '/MEDD/ {MEDD=$1};/STATE/ {STATE=$1};{print MEDD,STATE}'|tail -1

Hope this helps

Use ls' option -t to sort according to the files' time stamps. Assuming the file names' second and third last part being their modification time,

ls -lat RA* | head -2
-rw-rw-r-- 1 coerdtr coerdtr 0 Dez 22 17:01 RATE_STATE_SETUPS.20151222.20151222.170101.txt
-rw-rw-r-- 1 coerdtr coerdtr 0 Dez 22 15:01 RATE_MEDD_SETUPS.20151222.20151222.150102.txt

would yield the desired.

Your script does not produce that output; it would only print:

20151222.170101

And that would be from performing an alphanumeric sort on the strings:

20151222.170101
20151222.140101
20151222.150102
20151222.081212
20151222.121212

not from a numeric sort on:

170101
140101
150102
081212
121212

I would guess that you wanted to include the date as well as the time in the sort anyway, so you may have accidentally gotten the date and timestamp you wanted.

If you need to sort on the date specified by the file names instead of by the files' timestamps, you might want something more like:

ls RATE_STATE* | sort -t '.' -k3,4nr | head -1
ls RATE_MEDD* | sort -t '.' -k3,4nr | head -1

If it is something you'll be doing frequently, you could replace two invocations of head , one invocation of ls , and two invocations of sort with one invocation of awk with something like:

ls RATE* | awk -F. '
{	if($3 > dt[$1] || ($3 == dt[$1] && $4 > ts[$1])) {
		dt[$1] = $3
		ts[$1] = $4
		last[$1] = $0
	}
}
END {	for(i in last)
		print last
}'

which, with your sample filenames, would produce the output:

RATE_MEDD_SETUPS.20151222.20151222.150102.txt
RATE_STATE_SETUPS.20151222.20151222.170101.txt

but the order in which these two lines will be printed is unspecified.