I have a folder with the bulk of files in it of different types, i.e .pdf,.jpg,.png,.tiff etc., but all are named with the extension .JPG. How can I rename all of them with their original extensions? i.e pdf to pdf, tiff to tiff and so on.

I can find the file type by:

file 99.jpg
99.jpg: PDF document, version 1.3

Is there any script or program with which I can do this?

2 Answers 2


You can use the MIME type found by file:

#! /usr/bin/env bash
for f in ./*.JPG; do
    type=$(file -bi "$f")
    case "$type" in
        application/pdf) final="$base".pdf ;;
        image/png)       final="$base".png ;;
        image/tiff)      final="$base".tiff ;;
    if [ "$final" ]; then
        printf '%s --> %s\n' "$f" "$final"
        # mv -f "$f" "$final"

Add more types to the case if you need to (but leave out image/jpeg, since JPEG files already have the right extension). Review the changes, then uncomment the mv line when you're happy with the results.

  • You reverted my changes but your script will fail when files are named like -filename. The -- will take care of that. Jun 1, 2017 at 15:31
  • 1
    @val0x00ff Nope, I reverted that part of your script because it isn't needed. Because of ./*.JPG, file and mv will see ./-filename, not -filename. Please pay attention before "fixing" other people's posts. Jun 1, 2017 at 16:20
  • You know it's worthless to discuss this since my comment probably didn't arrive on time. Your original post didn't include the ./ and that's why I suggested the -- (End of options) syntax. Jun 6, 2017 at 7:24
  • @val0x00ff My edit was posted 6 minutes after the initial revision (what can I say, I'm an old fart). Your comment was posted almost 8 hours later, and it was about me reverting your changes, not about my initial revision. The reverted version was (and still is) 100% correct. Jun 6, 2017 at 7:36
  1. Generate the commands without running them.

    Use mimetype to generate a list of command strings, which is thereafter tweaked by GNU sed's substitute s command:

    cd ~/messed/up/folder/  # go where the files are...
    mimetype -M --output-format 'mv "%f" "%f%m"' *.JPG |
       sed 's#\.[^./"]*/\([^./]*"\)$#\.\1#'
  2. If some of the file extensions look a little too mime-ish, (i.e. .jpeg instead of .jpg, etc.), then add as many s commands as needed between sed ' and s, for example:

    sed 's/jpeg"$/jpg"/;s#\.[^./"]*/\([^./]*"\)$#\.\1#'
  3. Once the output looks good, run that with the GNU sed's evaluate e option. (Just put an e before the final '.) So the whole thing might look like:

    cd ~/messed/up/folder/  # go where the files are...
    mimetype -M --output-format 'mv "%f" "%f%m"' *.JPG |
        sed 's/jpeg"$/jpg"/;s#\.[^./"]*/\([^./]*"\)$#\.\1#e'
    ls  # show results

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .