Search code examples
bashshellnested-loops

remove files from subfolders without the last three


I have a structure like that:

/usr/local/a/1.txt
/usr/local/a/2.txt
/usr/local/a/3.txt
/usr/local/b/4.txt
/usr/local/b/3.txt
/usr/local/c/1.txt
/usr/local/c/7.txt
/usr/local/c/6.txt
/usr/local/c/12.txt
...

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, aola


Solution

  • 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)
     do     
         find $folder -maxdepth 1 -type f -name "*.txt" | xargs -r ls -1tr | tail -n+3 | xargs -r rm -f
     done
    

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