Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|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


$ for file in *; do [ -f "$file" ] && ( mv "$file" "$(echo $file | sed -e 's/ /_/g')" ); done
share|improve this answer
This looks like the safest, most portable approach to me. Magic syntax stuff is always a little sketchy and hard for someone else to understand what's going on; this answer uses one of the 2 obvious choices for "character substitution" -- the other being tr IE var=$(echo "$var" | tr ' ' _) – chris Aug 29 '13 at 12:21

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,$_);'
share|improve this answer

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
share|improve this answer
So this is way off in the weeds but you need to quote both "$1" and "${i// /_}". Also, that ${var///} stuff looks like a non-posix shell extension (bash perhaps)? – chris Aug 29 '13 at 12:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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