MacOS – Remove all files that match name in a list

automationdeletingfilemacosscript

I have a folder with a lot of images.

My client sent me a list of rejected images I need to delete from that folder.

The list is like this: _001,_002,_003,_004,_006,_007,RAM08953,RAM08995,RAM08996,RAM09039,RAM09060,RAM09087,RAM09101,RAM09104,RAM09115,RAM09126,RAM09170,RAM09171,RAM09172,RAM09176,RAM09188.

How can I easily run something that delete those files, or move those files inside a new folder or something without doing by hand? It can be an app, shell script or any tip.

Best Answer

You can delete a list of comma separated filenames using a CSV by using the following command:

for file in $( cat foo.csv | awk '{gsub(",","\n"); print $0}' ); do rm $file; done

You can make it safer by moving the file to the Trash instead of deleting it:

for file in $( cat foo.csv | awk '{gsub(",","\n"); print $0}' ); do mv $file ~/.Trash; done

How this works

This is a FOR/DO loop that first takes the contents of foo.csv and

  • cat foo.csv | This outputs the entire contents of the CSV file and pipes it to the next command
  • awk '{gsub(",","\n"); print $0} This line takes the output of the previous command and using the awk text processing utility then substitutes the comma (,) for the newline character (\n). It then outputs each item (print $0) on a separate line
  • each line becomes an "item" for the FOR loop to iterate.
  • for every item it will issue the command rm $file
  • You can delete/move/rename/whatever each file by modifying the command after do. (Eg. do mv $file ~/Foo/Bar/$file to move it to another folder.)