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
file1.jpg
% 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 *
do
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

done

The result:

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

% ls
file1.webp

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

  1. This internet site is my aspiration, rattling wonderful style and Perfect subject material. Salome Oswald Dahlia

Leave a Reply

Your email address will not be published.