Find and remove all but the latest file

Hi,

Would appreciate if someone could help me with the following requirement.

Say I have a directory where a file called abc_$timestamp.txt is created couple of times in a day.
So this directory would have files like

abc_2007-03-28-4-5-7.txt
abc_2007-03-28-3-5-7.txt
abc_2007-03-28-6-5-7.txt
abc_2007-03-28-5-5-7.txt

I need a script to search abc_*.txt and delete all but the latest file.

I know i could use a find command

find . type -f name -"abc_*" -exec rm{}

but , how would i keep the latest file

To retain the latest file created with name abc*.txt and to remove the remaining,

 ls -lt abc_*.txt | awk '{if(NR!=1) print $9}' | xargs -i rm {}

Another approach. This is based on the timestamp in the filename

ls -1 abc_*.txt | sort -r | tail +2 |  xargs -i rm {}

HTH,
Mona

Thank You Mona...could you please explain how it ensures that the latest file is not deleted?

In the first command, I am taking the files with name "abc_*.txt". Since i have used -t in the ls command, the file which is created recently will always come first. Then awk will pass the filenames other than the first record(this is the file we need to retain) to the xargs command to delete.

Second command is also quite similar. ls will take all the files starting with "abc_*.txt" and they are sorted by filename in descending order. The file with the latest timestamp will come first and the tail command will filter the first file(which is the latest) and pass the remaining filenames to the xargs to delete.

Hope my explanation is clear

thanks! tail +2 was throwing me off...its clear now...thanks again for your time