Bulk Rename files with Bash

Explore how to bulk-rename files quickly with Bash

Update: Mike Wilcox let me know that there is a much more simple way of doing this:

ls *old|sed 's/\(.*\)\.old/mv \1.old  \1.new/'|sh

Now that’s compact!

Here’s the original article:

Let’s say you have 100 files with a ".php’ extention, and you want to rename them so they have a “.html” extension. Here’s how you do it:

Create a file (e.g., rename.sh) with this code: #!/bin/bash

oldext=php
newext=html

for oldfile in `ls *.$oldext`; do
    [[ "$oldfile" =~ "(.*)\.$oldext" ]]
    newfile="${BASH_REMATCH[1]}.$newext"
    mv $oldfile $newfile
done

Give it execute permissions: chmod 755 rename.sh
Run it: ./rename.sh
Variations
Recursive Renaming To rename files recursively through sub-directories, use the find command instead of ls

Specify old and new extensions from command line Assign oldext to $0 and newtext to $1.