Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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

3 Answers 3

Try:

$ 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

 
discard

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.