Marco Falzone Marco Falzone - 26 days ago 16
Linux Question

Is there an efficient way to replace spaces with _ in filenames? (thousands of files)

I have a directory "FolderName" with 10,000 new files every day. Almost a half of those files are named as follows:

filename_yyyy-mm-dd_hh:mm


while the other half are named:

filename_yyyy-mm-dd hh:mm


(with space instead of underscore)

The script I'd like to set up should do the following:

Rename only the files containing a space in their name, skipping files that need no processing.

I cannot find a way to make the script efficient, I need to really skip the good half, my script tries to mv any file, and it's quite long and inefficient. Any good idea for a better design?

Thanks everybody

Answer

for f in "$(find . -name '* *')"; do mv $f $(echo $f | sed 's/\ /_/'); done will do it. There should be a better way using find's -exec option as well.

EDIT: If the function is put in a script, then find can be used directly:

cat <<EOF > space_to_underscore
#!/usr/bin/env bash
mv "$1" "$(sed 's/\ /_/' <(echo "$1"))"
EOF

find . -name '* *' -exec ./space_to_underscore {} \;

This will be faster than using a for loop.

Comments