How to recursivly delete all JPG files, but keep the ones containing "sample"

2

1

How can I find and delete all the .jpg files in a directory tree with the exception of the ones containing "sample" in their filename?

For example :

a.zip          ->  keep it  
b.jpg          ->  delete it  
a-sample.jpg   ->  keep it  
b-Sample.jpg   ->  keep it  

tachikoma01

Posted 2015-04-15T20:32:21.917

Reputation: 25

2Do you mean a-sample.jpg and b-Sample.jpg? – choroba – 2015-04-15T20:46:30.760

Yes I forgot to type the .jpg for a-sample.jpg – tachikoma01 – 2015-04-15T21:04:44.347

Answers

7

To delete all files ending in .jpg (case-insensitive) except for files with sample in the file name (case-insensitive:

find . ! -iname '*sample*'  -iname '*.jpg' -delete

This recurses through all directories in the tree starting at the current directory.

How it works:

  • .

    This specifies that we start with the current directory.

  • ! -iname '*sample*'

    This instructs find to ignore all files with sample in their name. The i in -iname makes this test case-Insensitive.

  • -iname '*.jpg'

    This condition, which is and'd with the previous one, looks for files ending in .jpg.

  • -delete

    This instructs find to delete all such files.

Before running the above command, you might want to test it. Run:

find . ! -iname '*sample*'  -iname '*.jpg'

This will print out the files of interest. If this list is good, then run the command again with -delete appended.

John1024

Posted 2015-04-15T20:32:21.917

Reputation: 13 893

Really right: it's never enough to remember to try before then to act, even more if the action is to delete. :-) – Hastur – 2015-04-27T18:26:42.773

2

In bash, you can use

shopt -s extglob

to enable negative matching:

rm !(*[Ss]ample*).jpg

To match subfolders too, turn on

shopt -s globstar

and use the double star:

rm **/!(*[Ss]ample*).jpg

choroba

Posted 2015-04-15T20:32:21.917

Reputation: 14 741

I should only suggest the OP to try in advance with ls **/!(*[Ss]ample*).jpg and only after checking to repeat the command with rm... just to be protected by typos. – Hastur – 2015-04-27T18:30:57.477