Replace a substring recursively in file names and folders

Replace a certain string in filenames recursively for all files in the current directory using find and and rename.
created by on 2013-09-04

Replace the string source with target in all files in the current directory and all sub-directories:

find . -type f -exec rename 's/source/target/' {} \;

Replace the string source with target in all directories in the current directory and all sub-directories:

find . -type d -exec rename 's/source/target/' {} \;

Example: replace ‘source’ with ‘target’

Content of the sample folder before the rename:

Rename-Sample
├── sample_source
│   └── file-source.txt
├── sample-source-2
│   └── sources.txt
└── source.txt

With the given regex “rename” will replace all occurances of “source” with “target”. And this will also include the components of the file path, so make sure to rename the directories first and then the files:

find . -type d -exec rename 's/source/target/' {} \;
find . -type f -exec rename 's/source/target/' {} \;

Result:

Rename-Sample
├── sample_target
│   └── file-target.txt
├── sample-target-2
│   └── targets.txt
└── target.txt

Warning!

Renaming files recursively can be dangerous when you are in the wrong directory 😉

Tags:
Fork allmark on GitHub