Possible Duplicate:
Recursive rename files and directories
I have a large directory of music files that is often changing as files and directories come and go. My preference is to make sure that file and directory names don't have spaces in them, so I replace them all with underscores.
I go into the main directory and run this command:
$ find -type d -exec rename 'y/\ /\_/' {} \;
The problem is that when there are subdirectories, this command seems to get lost and it will return errors. So if I have the following directory structure:
... and if I run the command, I get the following errors:
$ find -type d -exec rename 'y/\ /\_/' {} \;
find: `./Test 02': No such file or directory
find: `./Test 01': No such file or directory
find: `./Test 03': No such file or directory
And then the result is that my directory structure looks like this. Note the subdirectories still have spaces in them:
If I run the command again, I get these errors, even though it seems like maybe it renamed the directories in question:
$ find -type d -exec rename 'y/\ /\_/' {} \;
find: `./Test_01/Test A': No such file or directory
find: `./Test_01/Test C': No such file or directory
find: `./Test_01/Test B': No such file or directory
Finally, I run the command yet one more time, and I get no errors, and I have all directories and subdirectories named the way I want:
Obviously this requires running the command even more times when I have multiple subdirectories, which can get tedious.
How can I make it so that this command only has to be run once and it will rename all directories and subdirectories in one go?
My ultimate aim is to include this in a Bash script so that I can run it along with other similar housekeeping commands, so I need it to not return errors or need more input from me. Also, I'm running Ubuntu 12.04 if that makes a difference.
find
isn't aware that you've done so. So when it goes to dive into the directory and look for children, the directory isn't there any more. Unfortunately I cannot think of a simple way of fixing it (that wont break on weird filenames). A short script could do it, but not what I'd call simple. – phemmer Aug 26 '12 at 03:40find /tmp/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;
– Questioner Aug 26 '12 at 05:17