How can I delete everything except the listed files using the Find command?

I have a list of hidden files in the "list_files" file that should not be deleted in the current directory. How do I delete everything except them using the Find command? I tried, but this clearly doesn't work:

find . -iname ".*" \! -iname 'list_files'

      

0


a source to share


3 answers


Deleting files should always be done safely.

I will assume that you have a directory tree with hidden files and a list of subcategories of those hidden files that you want to keep. You want to remove all other hidden files.

Let's start with a list of hidden files.

find `pwd` -iname ".*" -type f > all-hidden-files.txt

      

Now, suppose you have a filter that will reduce the list to all the files you want to keep (creating lists of list_files). Here, SomeFilter can manually edit the list of files to keep the ones you don't want to delete.

SomeFilter all-hidden-files.txt > list_files

      



The following command will identify lines in all-hidden-files.txt that are not in filelist, giving you files to delete.

comm -3 all-hidden-files.txt list_files > removable-files.txt

      

Edit: just figured out that the input files in comm need to be sorted. So use this like

comm -3 <(sort all-hidden-files.txt | uniq) <(sort list_files | uniq) \
    > removable-files.txt

      

You can confirm that this works well for you and then delete the list of files generated with something like

for i in $(<removable-files.txt); do rm $i; done;

      

+1


a source


You can do this by calling exec with a bash script, something like this: -

find . -iname ".*" -exec bash -c "fgrep {} /tmp/list_files >/dev/null || rm -i {}" \;

      

Be very careful how you create your list of files. The list of excluded files must match the result generated by find, or you will delete all files that match your pattern.



I have installed the interactive option on rm and you can use it for testing. If you want to remove directories using this technique, you will need to change the rm options.

You might want to create your list of files using find from the same folder that you will use to run find to ensure that exceptions are thrown, although an absolute rather than a relative path would be better, i.e. safer, so your find will become

find /some/folder/name -name "some pattern" -exec ....

      

+1


a source


create a temporary directory in the original directory, move everything to the temp directory, move the files you want to keep to their original location, and then recursively delete the temporary directory. Since all traffic is on the same filesystem, it should be almost instantaneous with any decent filesystem, and it's pretty safe.

+1


a source







All Articles