Can anyone recommend a safe solution to recursively replace spaces with underscores in file and directory names starting from a given root directory? For example,
$ tree . |-- a dir | `-- file with spaces.txt `-- b dir |-- another file with spaces.txt `-- yet another file with spaces.pdf
becomes:
$ tree . |-- a_dir | `-- file_with_spaces.txt `-- b_dir |-- another_file_with_spaces.txt `-- yet_another_file_with_spaces.pdf
I've copied the question by another user which is the main question, but I need to add another issue:
I'm using the solution below:
$ find -depth -name '* *' -execdir rename " " "_" {} +;
It works, but only replaces the first whitespace found on an item (dir or file). Any ideas about how to make a loop to seek for spaces and stop when they're all gone?
If you don't have rename
available, or if you're not sure about which version you have, here's a way to achieve that:
find . -depth -name '* *' -execdir bash -c 'for i; do mv "$i" "${i// /_}"; done' _ {} +
You can use:
find . -depth -name '* *' -execdir rename 's/ /_/g' {} +
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With