Batch renaming part of filename’s with terminal command - Byron Salau

Posted by | February 29, 2012 | bash | No Comments

This is more of a personal post really beacause everytime I need to do this, I forget the command lines. I’ll be honest im not a bash ninja yet. However Drew Schrauf is and it was his shoulder that i tapped on to help me come up with the following commands.

The Wanted Outcome

Lets pretend we have a bunch of project files named similar to

  • Project-Pixelchild-Shared.txt; and
  • Target-Pixelchild-Debug.txt

We may have copied them from a previous project (My case) and the new project name is for example Codechild. So we want to rename these files and acheive

  • Project-Codechild-Shared.txt and
  • Target-Codechild-Debug.txt

Renaming your files

To do this we run a loop on our files. This assumes we want to replace everything in the current directory.

This first example is only a dry run because we are using “echo”. This basically means it will only show us an example of what will be changed without actually doing it yet. Neat.
for file in *; do echo mv "$file" "${file/Pixelchild/Codechild}"; done
This will find all the occurances of “Pixelchild” in the file names and replace them with “Codechild”. Then show you the log.

All look okay? Yes. Lets remove the echo and do it for real this time.
for file in *; do mv "$file" "${file/Pixelchild/Codechild}"; done

What if I wanted to replace occurances within the file content as well?

No problem. “sed” or “Stream Editor” has us covered. After you have renamed the filenames above run this command to replace the occurances within the files.

sed -i '' "s/Pixelchild/Codechild/" *

Quick Note about sed’s edit in place option

The extension after the -i flag is not optional and the solution is to send the zero-length extension with the (”) single quotes. You can read more about this from joe maller.