I have a bunch of files in a directory with 'spaces' in the filename.

How do I perform a bulk rename of all filenames with 'spaces' and replace them with an '_' char.

Looking at the other solutions, I've tried the following command w/o success:

find . -name '* *' -exec rename ' ' '_' {} +

find: rename: No such file or directory

link|improve this question
Are you using OS X? For some reason it doesn't come with rename(1), which is normally distributed as part of perl. – TRS-80 Apr 16 '10 at 8:31
feedback

3 Answers

Try:

$ for file in *; do [ -f "$file" ] && ( mv "$file" "$(echo $file | sed -e 's/ /_/g')" ); done
link|improve this answer
feedback

There's no direct answer, but most you will get are wrong in one way or another. Most likely, they will not use find properly, and you might get stupid results if any filename contains a ^J. 

Also if you have /lots/ of files, you probably don't want your script to spawn a sed or mv for each entry.

Here's a way to do it properly with basic Perl:

find . -print0 | \
  perl -e '$/="\000";' -ne '$o=$_;tr/ /_/;rename($o,$_);'
link|improve this answer
feedback

Thanks for the answers.

I found this one liner that did the trick:

for i in *\ *; do if [ -f "$i" ]; then mv "$i" ${i// /_}; fi; done

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.