Linux – Recursively fixing image file extensions in Linux

bashimageslinuxscript

I have a bunch of image files from misnamed scans/faxes I need to fix for our Linux users. It turns out we have a bunch of scans that are PNG files that are labled as *.jpg visa versa. Under Windows this was never an issue as Explorer/Office would just ignore the extension. But under Linux, Eye of GNOME etc end up just refusing to open the file because the contents don't match the extension.

Does anyone have any recommendations for a tool or a little piece of script that could do this? I could write a C program to do this, but that seems a bit overkill. Just sitting down and manually renaming manually isn't an option, there are thousands.

Edit: I see the file command will look at the actual contents of the file and display what it is. I'm not quite sure how to use the information from it though.

Best Answer

You'll want to iterate over the files that look like image files, call file to see what they really are, then rename them appropriately

for f in *.{jpg,JPG,png,PNG,jpeg,JPEG}; do 
    type=$( file "$f" | grep -oP '\w+(?= image data)' )
    case $type in  
        PNG)  newext=png ;; 
        JPEG) newext=jpg ;; 
        *)    echo "??? what is this: $f"; continue ;; 
    esac
    ext=${f##*.}   # remove everything up to and including the last dot
    if [[ $ext != $newext ]]; then
        # remove "echo" if you're satisfied it's working
        echo mv "$f" "${f%.*}.$newext"
    fi
done
Related Question