Search code examples
bashrenamefile-renamebatch-rename

Rename recursively repository and file names by replacing a pattern by another


I'd like to recursively rename all repository and file names under a specific directory that contain a given pattern.

I think I found a potential solution here with the following command:

find /your/target/path/ -execdir rename 's/special/regular/' '{}' \+

However it seems like I don't have the right rename command.

I installed Perl Rename package but I still don't have the Perl based rename command available. What can I do to be able to use this command?

Is there an alternative solution to this rename solution?

Let's say I have the following repositories and files:

BOOK1/
BOOK1/BOOK1_summary.txt
BOOK1/BOOK1_chapter1/BOOK1_chapter1.txt

I'd like to rename all occurrences of BOOK1 by BOOK-01 in repository and file names:

BOOK1-01/
BOOK1-01/BOOK1-01_summary.txt
BOOK1-01/BOOK1-01_chapter1/BOOK1-01_chapter1.txt

Solution

  • You could use the rename PERL utility which could be downloaded from this link.

    find  BOOK1 -depth -exec rename -n 's/^(.*)(BOOK1)(.*)$/$1BOOK1-01$3/' {} \;
    

    Dry-run output

    rename(BOOK1/BOOK1_summary.txt, BOOK1/BOOK1-01_summary.txt)
    rename(BOOK1/BOOK1_chapter1/BOOK1_chapter1.txt, BOOK1/BOOK1_chapter1/BOOK1-01_chapter1.txt)
    rename(BOOK1/BOOK1_chapter1, BOOK1/BOOK1-01_chapter1)
    rename(BOOK1, BOOK1-01)
    

    Remove the -n option from rename once you verify the dry-run result..

    Actual Output

     ls -R BOOK1-01/ # Used a recursive listing here.
    BOOK1-01/:
    BOOK1-01_chapter1  BOOK1-01_summary.txt
    
    BOOK1-01/BOOK1-01_chapter1:
    BOOK1-01_chapter1.txt
    

    Note : The -depth option with find is the key here. The find manpage says it process each directory's contents before the directory itself.