Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace part of filename recursively in terminal / .zsh?

how can I replace a part of the filename, of a certain type (.zip), with another string, recursively through all potential nested subdirectories?

This is my filesystem structure:

dir/
   |
   subdir/
   |
   filename_strToReplace.zip
   |
   subdir/
         |
         subdir
              |
              filename_strToReplace.zip
              filename_strToReplace.zip
              filename_strToReplace.zip

So as you can see, files whose filenames need to be modiffied can be nested few levels deep. I have some moderate terminal and shell experience but not real scripting.

I believe the solution is the combination of mv, RegEx (which I can use pretty decently) and a for loop.

For what it's worth I am on a Mac, using "default" terminal (haven't messed with this) with Oh-my-zshell.

Thanks!

like image 995
Alexander Starbuck Avatar asked Feb 07 '23 08:02

Alexander Starbuck


1 Answers

Using find and rename commands you can achieve that:

find . -name '*strToReplace*' | xargs -I{} rename 's/strToReplace/replacement/' {}

find search all files whose name contains strToReplace. Then rename uses a regex to rename those files.

like image 69
Gonzalo Matheu Avatar answered Mar 07 '23 20:03

Gonzalo Matheu