Needed script for the version file

I need some help with the logic and syntax for a shell script (ksh) that will search a directory and look for similar files and save only the 5 versions. The version number is in the file name.
However, the files are of varying name lengths and may have 1 or many files, with no limit to the number of files.
the input file

A_14122012.txt
A_15122012.txt
A_16122012.txt
A_17122012.txt

the output should contain the present and past one file

A_16122012.txt
A_17122012.txt

i used the below code please sugest the correct script

for file in `ls *.txt | sort -r | nawk -F"[2012|.]" '{if(_[$1]<2){print $0;_[$1]++}}' `
do
    echo $file
done

From you question, I presume that the file name uses the date in the format ddmmyyyy, and that makes it a little tricky. Better to use yyyymmdd if you can, so the most significant digits are first. If you are stuck with that, can you be sure that the files (once complete) are not edited?

If so, you could:-

ls -1rt *.txt|tail -5

If the file timestamps cannot be guaranteed, you could change the date format in the file name, then it is a much easier sort:-

ls -1 *.txt | sort -n +0.2

This format of sort may have been superseded by now, so check your manual pages for sort to be sure.

I hope that this helps,
Robin
Liverpool/Blackburn

---------- Post updated at 02:34 PM ---------- Previous update was at 02:32 PM ----------

Also see this thread:-
http://www.unix.com/shell-programming-scripting/210353-script-delete-files-folder-older-than-2-days.html#post302745441

Try:

ls -1 *.txt | sort -t_ -k1,1 -k2.5,2.8rn -k2.3,2.4rn -k2,2.2rn | nawk -F_ 'H[$1]++<2'

or, if your sort only supports the obsolescent key definitions:

ls -1 *.txt | sort -t_ +0 -1 +1.4 -1.7nr +1.2 -1.4nr +1 -1.2nr | nawk -F_ 'H[$1]++<2'