25 Feb 2019

Batch rename extensions

Another snippet, this time to batch rename the extension of a set of files to another, in my case I needed to rename *.html files as .mustache so, as before, (when I set up a scripts folder in my user folder and added it to my path in my .bash_profile), and added this text file:

1
2
3
4
5
#!/bin/bash
for file in *.$1
do
  mv "$file" "${file%.$1}.$2"
done

The first paramater you pass in $1 says what extension of file to find, and the second paramater $1 denotes the new extension. The for loop finds every file that matches *.$1 and does the line that begins ‘mv’ with each filename - the filename is placed inside a variable called “file”.

I’ve called this script batchrenameext and have placed it the scripts folder mentioned above and marked it as executable. Here’s that command plus an example:

1
2
chmod +x batchrenameext
batchrename html mustache
comments powered by Disqus