How to replace whitespaces in a filename?
Solution 1:
You shouldn't be using rename
to rename just one file, use mv
(1) instead.
Further, to escape whitepsace, prefix it with a \
:
"Ubuntu One"
→ Ubuntu\ One
Your command would be
mv bla\ bla.txt blabla.txt
-
the backslash tells bash that the next character is somehow special, e.g.
\a
for 'bell',\
for a literal space and so onsee
man ascii
(7) for more
Alternatively, since you are now using the correct command mv
, you can quote the filename if there are many spaces:
mv "bla bla.txt" blabla.txt
(This would be bla\ \ \ \ bla.txt
in escaped form)
-
In bash, quoted strings (single or double quotes) are treated as a single argument, whereas unquoted strings will be split into multiple arguments, like this:
["mv", "bla", "bla.txt", "blabla.txt", ]
and
mv
expects:["mv", "source", "destination", ]
Note: typing 'mv' and the first few characters of the filename and pressing TAB will give you the escaped version of the file name, making renaming quick and easy.
rename
is used to batch-process the renaming of files using regular expression, as demonstrated in the example from its man-page:
rename 's/\.bak$//' *.bak
To strip any occurence of .bak (at the end of the string [$]) from all of the files matching "*.bak".
Solution 2:
rename is specialized command for bulk renaming. Unintuitively, what we normally call "renaming" is actually a "move" to a new name:
mv 'bla bla .txt' blabla.txt
Solution 3:
rename "s/\s//g" "bla bla.txt"
s is the sed Substitute command.
\s is for whiteSpace
You are replacing with nothing. Else replacement string goes after second forward slash.
g is for Global, i.e. replace every instance. Omitting g replaces only the first instance.
This command will replace whitespace with underscore in all the files:
rename "s/\s/_/g" *