I want to free up some space by deleting redundant files within many subdirectories. However I always want to retain the last file of a file stem. For example I have an assortment (next to other files that should not be touched) similar to this:
FILE_1-1 FILE_1-2 FILE_1-3 FILE_2-1 FILE_2-2
within a whole bunch of branching subdirectories. I want to keep FILE_2-2 in this instance, but in another folder it would be FILE_3-1 or whatever. Always the last file. I know how to get rid of all of them using the find command which traverses the subdirectories nicely:
find . -name "FILE_*" -type f -delete
How can I exclude the last FILE_* within each directory where removal happens using the find command? Googling (https://www.unix.com/shell-programming-and-scripting/36639-find-remove-all-but-latest-file.html) turned up the following:
ls -1 FILE_* | sort -r | tail +2 | xargs -i rm {}
But this command does not work with branching directories, does it?
sortfunctionality if you have more than one digit in the sequence.FILE_1-10comes lexicographically beforeFILE_1-2. Padding with zeros (egFILE_1-002) would make numeric and lexicographic order consistent.FILE_3-5. I hope this helps to keep it simple.ls ... FILE_*.txtwhile your sample filenames do not end in.txt