Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash recursively replace many spaces on names

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?

like image 377
Alex Ferro Avatar asked Nov 05 '14 20:11

Alex Ferro


2 Answers

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' _ {} +
like image 122
gniourf_gniourf Avatar answered Sep 28 '22 17:09

gniourf_gniourf


You can use:

find . -depth -name '* *' -execdir rename 's/ /_/g' {} +
like image 28
anubhava Avatar answered Sep 28 '22 16:09

anubhava