Needed shell script to get the latest file based on date

hi i need the shell script to get the file with latest date.

for example in my input folder i have files like

file_20130212.txt
file_20130211.txt

now my output folder should have the file with latest date i.e..file_20120212.txt

i want to get the latest file .. i.e is should take the value 20130212 from the file and should convert it to 2013-02-12 and should check with the system date and should return the latest file based on the date format..

thanx in advance....

Since the date is in YYYYMMDD, a numeric sort would do the trick.

Try something like..

ls file_*.txt | sort -t"_" -nrk2.1,2.8 | head -1

what is that -nrk2.1,2.8 in that above code..?

Reverse numeric sort ( -nr) on char 1 to 8 ( 2.1,2.8) of second field (20130212.txt) while using "" as the field separator ( -t"")

1 Like

actually i got a change in my requirement can u solve the above problem..

Since the format is YYYYMMDD, the alphabetic sort in ls will do it:

ls file_*.txt | tail -1

I am confused with the new requirement.
Do you want to get the latest file based on last modified/create date/time or the one which is present in the filename.