Delete all not jpeg files
Deleting based on file mimetype
To delete all non-jpeg regular files in the current directory or its subdirectories, use:
find . -type f -exec bash -c 'file -bi "$1" | grep -q image/jpeg || rm "$1"' none {} \;
This approach is safe for all file names. It will work even if the file names have newlines or other difficult characters in them.
How it works
-
find . -type f
This starts a
find
command, restricting the files found to regular files,-type f
. -
-exec bash -c 'file -bi "$1" | grep -q image/jpeg || rm "$1"' none {} \;
For all the files found, this runs a bash command to test the file's type. In particular,
file -bi "$1" | grep -q image/jpeg
will return true iffile
reports that the file has mimetypeimage/jpeg
. The operator||
assures that therm
command which follows is executed only for files which failed the jpeg test. Thus, all non-jpeg files are deleted.
Deleting based on file name
To delete all files whose names do not end in .jpeg
:
find . -type f ! -name '*.jpeg' -delete
This approach is also safe for all file names. It will work even if the file names have newlines or other difficult characters in them.
How it works
-
find .
Find all files in the current directory and its subdirectories
-
-type f
Restrict ourselves only to regular files
-
! -name '*.jpeg'
-name '*.jpeg'
would find all files whose names end in.jpeg
. The exclamation mark,!
, however, means negation. So,! -name '*.jpeg'
restricts our search to files whose names do not end in.jpeg
. -
-delete
This tells
find
to delete the files that match the above criteria.
Testing
To test the command, leave off the -delete
:
find . -type f ! -name '*.jpeg'
This will show you what files would be deleted when the -delete
action is used.