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
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*'
find to ignore all files with
sample in their name. The
-iname makes this test case-Insensitive.
This condition, which is and'd with the previous one, looks for files ending in
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
In bash, you can use
shopt -s extglob
to enable negative matching:
To match subfolders too, turn on
shopt -s globstar
and use the double star: