One-liner: how to change file extensions according to their type

What if you have PNG or WEBP files, saved with .jpg extension? Here’s a one liner to rename them accordingly. You need mediainfo package:

sudo apt-get install mediainfo

Imagine we have file1.jpg in the current directory:

% ls
% file file1.jpg
file1.jpg: RIFF (little-endian) data, Web/P image, VP8 encoding, 800x800, Scaling: [none]x[none], YUV color, decoders should clamp

No problem just rename it! But what if we have a hundred?

for i in *
oldext=`echo "$i" | sed -e 's/^.*\.\([A-Za-z][A-Za-z]*\)$/\1/'`
echo "Old ext=$oldext"
newext=`mediainfo "$i" | egrep "^Format[[:space:]]+:" | sort -u | tr '[A-Z]' '[a-z]' | sed -e 's/.* \([a-z][a-z]*\)/\1/' -e 's/jpeg/jpg/'`
echo "New ext=$newext"

oldname=`echo $i | sed -e 's/\.'$oldext'$/.'$oldext'/'`
newname=`echo $i | sed -e 's/\.'$oldext'$/.'$newext'/'`

echo old=$oldname new=$newname
mv -i $oldname $newname


The result:

Old ext=jpg
New ext=webp
old=file1.jpg new=file1.webp

% ls

One thought on “One-liner: how to change file extensions according to their type”

Leave a Reply

Your email address will not be published.