Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search+replace strings in filenames

Tags:

bash

Using bash, how can I search for all occurrences of the substring 'foo' in all filenames (including folders) contained recursively in a directory and replace them them with 'bar'?

For example, if the current structure looks like:

-foo_test     - fooo.txt     - xfoo         - yfoo.h - 1foo.c 

It should look like this after running the bash script:

-bar_test     - baro.txt     - xbar         - ybar.h - 1bar.c 
like image 501
Cam Avatar asked Aug 24 '11 07:08

Cam


People also ask

How do I replace a filename in bulk?

Type the following command to rename the part of the file name and press Enter: ren OLD-FILE-NAME-PART*. * NEW-FILENAME-PART*. * In the command, replace "OLD-FILE-NAME-PART" and "NEW-FILENAME-PART" with the old and new parts of the filename.


1 Answers

Both variations shown here using work correctly on OPs test structure:

find . -depth -name '*foo*' -execdir bash -c 'mv -i "$1" "${1//foo/bar}"' bash {} \; 

or, if you have a very large number of files and want it to run faster:

find . -depth -name '*foo*' -execdir bash -c 'for f; do mv -i "$f" "${f//foo/bar}"; done' bash {} + 

EDIT: As noted in the comments, my earlier answer using a find command that did not use the execdir option and using rename has problems renaming files in directories that contain foo in their name. As suggested, I have changed the find commands to use -execdir, and I have deleted the variation using the rename command since it is a non-standard command.

like image 55
Adrian Pronk Avatar answered Sep 22 '22 15:09

Adrian Pronk