I have a structure like that:
ls -tr *.txt | head -n-3 |xargs rm -f
find /usr/local/**/* -type f
maxdepth options to find for one level, sorting files by last modification time,
tail to ignore the oldest modified 3 files and
-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.