How to rename files in ubuntu, recursively, using grep and rename not find?

There are gazillions of questions and answers regarding how to rename files. I'm new to Linux and this myriad of possible ways and different results and different configurations confuses me.

For example:

  • rename works, but not recursively
  • grep works recursively, but can't be used to search for file and directory names, instead of file contents
  • find works, but has a long ugly syntax when you want to search using regular expressions.

And also a lot of answers on ask ubuntu and stackoverflow do not work for me and I don't know how to debug and troubleshoot them.

So, forgive me to ask it one more time.

I'm searching for a clean, memorizable way of:

Renaming files recursively using simple regular expression.

I already do it for the content of files using this syntax:

grep -rl search_regex | xargs sed -i 's/old/new/g'

It works without a lot of frustration. It works out of the box. It just works. I'm searching for a workable solution that is neat and clean. Can you help me please?


Solution 1:

Cannot find anything long and ugly about find:

find . -regex 'search_regex' -exec rename 's/old/new/g' {} +

Solution 2:

You can make rename recursive if that's the syntax you prefer:

shopt -s globstar
rename 's/old/new/' **/*

Bash's globstar option makes ** match 0 or more directories or files recursively, so **/* will recurse down the entire directory tree. You just need to write your search pattern as a glob instead of a regular expression. For example, to rename all files whose name contains foo, you would do:

shopt -s globstar
rename 's/old/new/' **/*foo*