I know that there are many questions about adding extension to a multiple files. But none of them could get my job done.

I have a huge list of images without extension, most of them are png, but there are jpg files also and maybe tiff.

How could I rename them correctly?


3 Answers 3


Perhaps like this:

for f in /some/dir/*; do
    type="$( file -bi -- "$f" )"
    case "${type%%;*}" in
        image/jpeg) ext=jpg ;;
        image/png)  ext=png ;;
        image/tiff) ext=tiff ;;
        *) printf '%s: %s: unknown file type\n' "${0##*/}" "$f" >&2; ext='' ;;
    if [ -n "$ext" ]; then mv -n -- "$f" "${f}.${ext}"; fi
  • Please note this answer has been edited since I posted it. I disagree with the edit. Sadly, I can no longer delete my answer, since it has been already accepted. shrug
    – lcd047
    May 20, 2015 at 11:30
  • You should also revert the ${f%.*} back to ${f}. Nobody wants their photo.of.bigfoot renamed to photo.of.jpg. ;-)
    – Dubu
    May 20, 2015 at 11:38
  • @Dubu: Right, sorry.
    – lcd047
    May 20, 2015 at 11:47

Another way with exiftool:

exiftool -r -ext '' '-filename<$filename.$filetype' .

this recursively renames all image files without extension under current directory . to filename.TYPE where TYPE is JPEG, PNG, TIFF etc.

Or, to rename only files of type JPEG/PNG/TIFF that have no extension:

exiftool -if '$filetype eq "JPEG"' -filename=%f.jpg \
-execute -if '$filetype eq "PNG"' -filename=%f.png \
-execute -if '$filetype eq "TIFF"' -filename=%f.tiff \
-common_args -r -ext '' .
  • Thank you. Very elegant. However it requires installing libimage-exiftool-perl May 20, 2015 at 11:20
  • I mean that I have a huge number of files. And yes, all of them are without extension. May 21, 2015 at 16:47
  • 1
    @OsamaAbbas - got it. In that case you already have lcd047's working solution that doesn't require additional tools. May 21, 2015 at 16:53
  • @don_crissti - assuming the extension is present but incorrect, how would someone use your solution to rename the file to the correct extension? For example, lets assume x.png is really x.jpg but simply has the wrong extension. How can I use your solution to rename the file to x.jpg?
    – J363
    Sep 22, 2016 at 7:15
  • ok, I got it I just removed the -ext '', you were using that to express a lack of a file extension. Nice solution.
    – J363
    Sep 22, 2016 at 7:35

Not sure if this answers your question, but if you want to know which image type (PNG, JPEG, etc) is a specific file, you can use the file command:

file myimage.xxx

myimage.xxx: PNG image data, 837 x 814, 8-bit/color RGB, non-interlaced
  • Thank you for your help. I know file but my question is how to use its result to rename multiple files. May 20, 2015 at 10:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.