I have exercise, in which I have to delete all files, which are not jpeg.
I tried find -type f |xargs file| grep -iv 'jpeg', but it doesn't work.
I have exercise, in which I have to delete all files, which are not jpeg.
I tried find -type f |xargs file| grep -iv 'jpeg', but it doesn't work.
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.
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 if file reports that the file has mimetype image/jpeg. The operator || assures that the rm command which follows is executed only for files which failed the jpeg test. Thus, all non-jpeg files are deleted.
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.
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.
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.