Deleting old files from a dir

Hi,

I have a folder/dir which have file names as below.

file1.txt
file2.txt
file3.txt
.
.

Such files are added to the folder daily. I have to keep only latest 10 files in the folder and delete the old files.

I have tried several ways. But couldn't find a better logic.

ls -t|tail -n 10;ls|sort|uniq -u|xargs rm

or 

rm `ls -t | awk 'NR>10'`

According to the standards, ls -t|tail -n 10 should give you the 10 newest files. And, ls -tr|tail -n 10 should give you the 10 oldest files.

However, on some systems, ls -t gives you multi-column output even when the output is not directed to a terminal. For, those systems, you also have to use the -1 (digit one; not letter ell) option to force single column output.

Try:

echo rm $(ls -t1 | awk 'NR > 10')

If that shows you the command you want to execute, remove the echo to actually run it.

1 Like