views:

370

answers:

3

I have a list of hidden files in a file "list_files" that should not be removed in the current directory. How can remove everything except them with a Find-command? I tried, but it clearly does not work:

find . -iname ".*" \! -iname 'list_files'
+1  A: 

You can do this by invoking exec with a bash script so something like this :-

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

Be very careful how your construct your list of files. The list of files to exclude must be identical to the output produced by find or you will delete all files matching your pattern.

I have put the interactive option on to rm and you may wish to use this for testing. If you wish to remove directories with this technique then you will need to modify the rm options.

You may wish to construct your list of files using find from the same folder you will use to run the find to ensure the exclusions will be honoured although an absolute rather than a relative path would be a better i.e. safer option, so your find would become

find /some/folder/name -name "some pattern" -exec ....
Steve Weet
+1  A: 
nik
A: 

create a temporary directory in your source directory, move everything to the temp directory, move the files you want to save back up to the original place, and then recursively remove the temp directory. Since the moves are all on one filesystem, it should be almost instantaneous with any decent filesystem, and this is pretty safe.

dannysauer