How to Delete Files in a Folder Except Those Listed in list.txt

deletefindrm

Assume in folder /photo have many files like

1.jpg
2.jpg
3.jpg
4.jpg
5.jpg
6.jpg
7.jpg
8.jpg
9.jpg
10.jpg

I have a file name nodeletelist.txt in this text file have name of not delete files list like

1.jpg
2.jpg
3.jpg
nodeletelist.txt

How to delete files:

4.jpg
...
10.jpg

except files 1.jpg, 2.jpg, 3.jpg and nodeletelist.txt which in nodeletelist.txt?

Best Answer

For me the simplest and easy to remeber and working also for very many files (thought would break on newline within filename but if You would have that You would have to think about Your list):

cd /photo
ls -1 | grep -v -x -f nodeletelist.txt | xargs -d "\n" -P 0 rm -f

If there is something else in the directory (subdirs or different files, which I do not assume as You include Your txt in the list) I would use find I instead of ls (find . -maxdepth 1 -type f -name "*.jpg" for example).

Related Question