Search code examples
imagebashscriptingpngjpeg

Rename a bunch of PNG images with ".jpg" extension to ".png"


So I have a folder with thousands of image files, all of them saved as .jpg.

The problem is that some of those files are actually PNG image files, so they don't open in a lot of programs, unless I manually change their extension to .png. For example, the Ubuntu image viewer throws this error:

"Error interpreting JPEG image file (Not a JPEG file: starts with 0x89 0x50)"

I've already ran a hexdump of some of these files to confirm this error and it checks out.

I'm looking for a simple way to find all the files with the wrong extension among the other files and change their extension. How would I do this with a bash script for example? So far I have no idea. All help apreciated!


Solution

  • for f in *.jpg ; do
      if [[ $(file -b --mime-type "$f") = image/png ]] ; then
        mv "$f" "${f/%.jpg/.png}"
      fi
    done
    

    This gets a list of .jpg files, then for each calls the file utility on it to get the mime type. If that's image/png, then it renames the file using a string manipulation substitution.