Skip to content
Advertisement

delete all files except a pattern list file

I need to delete all the files in the current directory except a list of patterns that are described in a whitelist file (delete_whitelist.txt) like this:

(.*)dir1(/)?
(.*)dir2(/)?
(.*)dir2/ser1(/)?(.*)
(.*)dir2/ser2(/)?(.*)
(.*)dir2/ser3(/)?(.*)
(.*)dir2/ser4(/)?(.*)
(.*)dir2/ser5(/)?(.*)

How can I perform this in one bash line?

Advertisement

Answer

Any bash script can fit on one line:

find . -type f -print0 | grep -EzZvf delete_whitelist.txt | xargs -0 printf '%sn'

Check the output and then, if it’s OK:

find . -type f -print0 | grep -EzZvf delete_whitelist.txt | xargs -0 rm
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement