aola aola - 1 year ago 48
Bash Question

remove files from subfolders without the last three

I have a structure like that:


I want to delete all the files *.txt in subfolders except the last three files with the greatest modification date, but here I am in current directory

ls -tr *.txt | head -n-3 |xargs rm -f

I need to combine that with the code:

find /usr/local/**/* -type f

Should I use the maxdepth option?

Thanks for helping,

Answer Source

Added maxdepth options to find for one level, sorting files by last modification time, tail to ignore the oldest modified 3 files and xargs with -r to remove the files only if they are found.

 for folder in $(find /usr/local/ -type d)
     find $folder -maxdepth 1 -type f -name "*.txt" | xargs -r ls -1tr | tail -n+3 | xargs -r rm -f

Run the above command once without rm to ensure that the previous commands pick the proper files for deletion.