Skip to main content
7 of 11
added 4 characters in body
Emmanuel
  • 4.3k
  • 2
  • 26
  • 31

I realize that any discussion asking how to delete files must be taken with grate care. My first answer was too hasty I didn't take the fact that the filelist could be malformed. 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:

sed -e 's,^,^,' -e 's,$,$,'  filelist  > newfilelist 

build the rm commands

cd your_directory
ls | egrep -vf newfilelist   | xargs -n 1 echo rm  >  rmscript

Check if the rm script suits you (You can do it with "vim" or "less").
Then perform the action :

sh -x rmscript

If the files have spaces in their name (if the files have the " in the name that will not works) :

ls | egrep -vf newfilelist  | sed 's,^\(.*\)$,\\"\1\\",'  | xargs -n 1 echo rm  > rmscript

of course the filelist should not be in the same directory

EDITED :

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 `egrep -vf absorbed all the stream. I added a command to put a ^ and a $ around each file name

Emmanuel
  • 4.3k
  • 2
  • 26
  • 31