2

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  
  • 2
    Do you mean a-sample.jpg and b-Sample.jpg? – choroba Apr 15 '15 at 20:46
  • Yes I forgot to type the .jpg for a-sample.jpg – tachikoma01 Apr 15 '15 at 21:04
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.

  • Really right: it's never enough to remember to try before then to act, even more if the action is to delete. :-) – Hastur Apr 27 '15 at 18:26
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
  • 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 Apr 27 '15 at 18:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.