Bulk Rename in Bash

Here’s a relatively simple way to rename a bunch of files from the command line. It uses sed within a command substitution to compute the new names from the old names.

In this example, we’re renaming files that start with “ABC” to start with “XYZ” instead:

  for i in ABC*; do mv $i $(echo $i | sed -e s/^ABC/XYZ/); done

You’ll have to use shell globbing (wildcards) in the first part, to determine which files will be the source of the renaming, and regular expressions in the second part to translate the old names into the new names.

It’s a good idea to use echo in place of mv before running this, to see what the results will be, so you don’t make a mistake.

Depending on the situation, you may need to adapt this for your particular needs. For example, if you have too many files to rename, you would need to use xargs. Or sed might not be up for the task of transforming the names that you want. Or you might need to use find to find files within a hierarchy. As with any UNIX idiom, there are hundreds of variations on the theme.

Leave a Reply

Your email address will not be published. Required fields are marked *