Marco Falzone Marco Falzone - 1 year ago 71
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:


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 Source

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"))"

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

This will be faster than using a for loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download