Bulk Rename files with Bash

Explore how to bulk-rename files quickly with Bash

Update: Mike Wilcox provided this much more simple way of bulk-renaming files:

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:

  1. 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
    
  2. Give it execute permissions: chmod 755 rename.sh
  3. 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.

Links