I have an interesting question, one that may, or may not be easy :( I've been trying to work out a way to do it integrating options of the 'find' command on linux.
Basically, I have a directory tree, within which could be multiple examples of the files that either need keeping, or deleting. All the files share the same extensions, for sake of argument .XX (although the idea would be to be as generic as possible so it could be any file). I want to delete all .XX files within the directory tree, EXCEPT where the files lie within a specific folder (will always be the same title, in the example called YYY).
Say I have to following structure (where each sub directory could end up containing many many many files that I don't want to touch or affect alongside those that I do):
folder_root: | |--> Subdir_1/interesting_file_1.XX |--> Subdir_1/interesting_file_2.XX |--> Subdir_1/unrelated_interesting_file_1.AA |--> Subdir_2 |--> Subdir_3/interesting_file_3.XX |--> YYY/interesting_file_4.XX |--> YYY//interesting_file_5.XX
I want to be left with:
folder_root: | |--> Subdir_1/unrelated_interesting_file_1.AA |--> YYY/interesting_file_4.XX |--> YYY/interesting_file_5.XX
The note is, the directory YYY could be anywhere, and there could be many of them, so having a list of directory paths that need excluding to hand to build a large exclusion list isn't possible.
First I did a basic
Find as such:
find . -iname "*.XX". Then I looked at adding the
-printf "%h\n" to output the directories that contain the .XX files. What I'm struggling to do, is take that outputted list, and use it to inform the process of deleting, or as the case may be, not deleting. I suppose I could use
grep to remove any YYY folders from the output into a temp file, use a
while read loop, then
popd to move in, and then out of the folders, using a simple
find . -iname "*.XX" -delete within each sub-directory (then using the
-empty switch within find to clean up any empty directories left as a result). This does however, feel very blunt force, with a very large sledgehammer, that could be very system intensive, especially when dealing with potentially hundreds of sub-directories.
I'm interested if there is a 'better' way, that is slicker, generally less intensive overall and reliable (especially if you end up having to run it three or four times for three or four different file types)?
There may not be, but its worth a quick ask :) Why use a sledgehammer when a simple hammer would do!? :)
Final note, I cannot add additional shell commands to the system (and the systems used are a mix of Ubuntu and Centos), so where possible, it would need to use the pre-existing command set (assume no other modules are installed except Tree, which I do know about). I hope the question is clear, and 'generic' enough to be useful to others in different situations if a simple answer is found.