Take the 2-minute tour ×


share|improve this question
add comment

migrated from stackoverflow.com Jun 12 '11 at 3:35

This question came from our site for professional and enthusiast programmers.

5 Answers

up vote 15 down vote accepted

Escape the space, e.g. Spring\ 2011, or use quotes, e.g. 'Spring 2011'. In the future, it's typically a bad idea to use file names with spaces in them on any *NIX.

If you've got rename, you can use this:

rename ' ' '_' [filenames...]
share|improve this answer
+1 -- beat me to the answer by about 3 seconds. –  zellio Jun 8 '11 at 19:42
Do you know is there anyway to do this for all the files at once? –  Phil Braun Jun 8 '11 at 19:55
@phil for the rename command, specify a pattern for filenames that matches all the files you want to rename (e.g. if there's a common prefix/suffix). –  Rafe Kettler Jun 8 '11 at 20:04
Why is it a bad idea? It's the responsibility of the programmer to handle filenames properly. –  glenn jackman Jun 9 '11 at 14:28
@glenn because spaces in a filename have to be either escaped or quoted in the shell, which is extra effort for anyone writing scripts and can be error prone. –  Rafe Kettler Jun 9 '11 at 15:16
show 2 more comments

If your machine has the rename command, then this will change all spaces to underscores in all files/dirs in the current working directory:

rename 's/ /_/g' *
share|improve this answer
add comment

If you don't have rename or prefer to use just the shell:

for f in *\ *; do mv "$f" "${f/ /_}"; done

Just for understanding:

${f} is a secure way to reference $f.

${f/str/new_str} is a bash-specific sting substitution feature. It shouldn't work on other shells.

It's clever, because it has no external dependencies.

share|improve this answer
+1 nice answer. –  glenn jackman Jun 22 '11 at 17:09
add comment

mv "Spring 2011.file" Spring_2011.file should tell the command-line to take the quoted string as a single input.

share|improve this answer
add comment

I had a bunch of files with ".jpg;1" as the suffix. I fixed it by:

rename 's/;1//' *
share|improve this answer
How does this answer the question? –  nhinkle Jun 22 '11 at 18:14
add comment

Your Answer


