You should be able to use the
mimetype utility - from
mimetype - Determine file type
mimetype [options] [-] files
This script tries to determine the mime type of a file using the Shared
MIME-info database. It is intended as a kind of file(1) work-alike, but
uses mimetypes instead of descriptions.
So for example:
$ mimetype somefile
However, by default,
mimetype will "believe" the extension if present - so:
$ cp somefile somefile.gif
$ mimetype somefile.gif
You can tell it to use only the file's magic bytes to do the determination by adding the
$ mimetype -M somefile.gif
and you can add
-b to give a
$ mimetype -bM somefile.gif
If you wanted to script the renaming, I'd suggest something like this:
while read -r -d '' f; do
mt="$(mimetype -bM "$f")"
case "$ext" in
echo mv -v "$f" "$f.$ext"
echo "skipping mimetype $mt... "
done < <(find -type f -print0)
- it doesn't actually rename anything as written: the
echo mv just outputs what it would do - please check and double check that it is behaving as expected on your files before removing the
- it only operates on
png files: if there are other image types, you will need to add those explicitly
- it will rename (add an additional extension to) any files it considers to have the wrong extension, based on magic bytes
There may be other - easier - options using tools like