I have about 12000 images of different file types but every one of them was renamed *.jpg.
Now I want to give them their proper extensions back, how can I do it
I have about 12000 images of different file types but every one of them was renamed *.jpg.
Now I want to give them their proper extensions back, how can I do it
You can do it relatively easily in bash:
This is the same idea as @A.B's answer but using shell globs instead of
find
. The${f%%.*}
is the filename without its extension. The-0
of thefile
command makes it print a\0
after the file name which we then use togrep
the file type. This should work with arbitrary file names, including those that contain spaces, newlines or anything else. The${type,,}
is a trick to get lower case extensions. It would convertPNG
topng
.You didn't say in your question, but if you need this to be recursive and descend into subdirectories, you could use this instead:
The
shopt -s globstar
will enable bash's globstar option which lets**
match subdirectories:The script below can be used to (recursively) rename an incorrectly set extension,
.jpg
, to the correct one. In case it finds an unreadable file, it will report it in the script's output.The script use the
imghdr
module, to recognize the following types:rgb
,gif
,pbm
,pgm
,ppm
,tiff
,rast
,xbm
,jpeg
,bmp
,png
. More on theimghdr
module here. The list can be extended with more types, as mentioned in the link.As it is, it specifically renames files with the extension
.jpg
, as mentioned in the question. With a minor change, it can be fit to rename any extension, or a specific set of extensions, into the correct one (or with no extension, like here).The script:
How to use
rename.py
Run it by the command:
Note: My approach seems to be too complex. I would prefer terdons answer in your place.
You can use the command
file
to to determine the file type:With this information, the files can be renamed:
Please do a test before you apply the command to your images
Example