I have a directory with 1000+ files. In a text file, I have about 50 filenames, one per line. I'd like to delete all the files in the directory whose filenames don't correspond with an entry on the list. What's the best way to do this? I started a shell script, but couldn't determine the proper command to determine in the filename is on the list. Thanks.
I realize that any question asking how to delete files must be taken with great care. My first answer was too hasty I didn't take the fact that the filelist could be malformed to be used with egrep. I edited the answer to reduce that risk.
That should work for the files that has no space in the name:
First rebuild your filelist to be sure to match the exact file name:
build the rm commands
Check if the rm script suits you (You can do it with "vim" or "less").
If the files have spaces in their name (if the files have the
of course the filelist should not be in the same directory
The Nathan's file list contained names that where matching all the files in the directory (like "html" matches "bob.html"). So nothing was deleted because
If you put the contents of the directory into a file like so:
Open filelist with a text editor, and remove all the files except the ones YOU WANT TO DELETE. That's bolded because it's the opposite approach to the answer above
If you see your list of files output to the screen replace echo with
Pre-construct the arguments to
Run the below script.
The script is as below.
P.S: Probably, if you wish this to be saved as a script and run it, you can add the script name also using
Though it is not required, I prefer to do it because there will be no regrets later. I tested for a small set of files and it worked in my system. However, if you want to be sure, try in a