How do I rename files with spaces using the Linux shell?

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...]

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' *

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

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

Broken down:

  • *\ * selects all files with a space in their name as input for the the for loop. The pattern *X* selects all files with X in their name, and for the special character space, we have to escape it with a slash so that bash doesn't treat it as separating different arguments.
  • The quotes around "$f" are important because we know there's a space in the filename and otherwise it would appear as 2+ arguments to mv.
  • ${f//str/new_str} is a bash-specific string substitution feature. All instances of str are replaced with new_str.