I named a number of files with spaces in them, and I want to replace the space with "_". However, every time I write a command in the shell with the file name (eg "Spring 2011"), the shell doesn't recognize the file or directory. What can I do about this? Is there any way to use the unicode character for a space?

link|improve this question
feedback

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 10 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...]
link|improve this answer
+1 -- beat me to the answer by about 3 seconds. – Mimisbrunnr 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
1  
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 1 more comment
feedback

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' *
link|improve this answer
feedback

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

link|improve this answer
feedback

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

for f in *\ *; do mv "$f" "${f// /_}"; done
link|improve this answer
+1 nice answer. – glenn jackman Jun 22 '11 at 17:09
feedback

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

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

Your Answer

 
or
required, but never shown