Is it possible, in Linux, to rename a file from something without spaces to something containing spaces?

I know I can create directories and files with spaces by doing:
mkdir "new dir" and:
touch "new file.txt"

I want to rename files from:
imgp0882.jpg to something like:
20091231 1243 some topic.jpg

And how would it look in a shell script that uses parameters like:
for i in *.jpg do
rename "$i" "$somepath/$mydate $mytime $mytopic$extension"


A little background:

  • I'm new to Linux (using PCLinuxOS 2009.2), coming from Windows, and I've written myself a little shell script to download files from my camera and then automatically rename them according to a date-and-topic pattern. As you can guess by now, I'm stuck on the bit about renaming.
  • If you want to see my script, here's a copy.
  • I'm not using jhead for this renaming because that only works with JPEG files but I want a single solution for any media format including videos.
  • You should know that the operations of moving and renaming in Linux are basically equivalent, and are both done using mv. The command called rename is for renaming a whole batch of files at once according to some pattern. Its use is more complex. – Ryan Thompson Jan 28 '10 at 22:45
  • Thanks, that's a great comment, as it's very different from the (not) same DOS/Windows commands. Obviously mv is the way to go. – Torben Gundtofte-Bruun Jan 30 '10 at 10:48

Maybe you need to just put quotes around whole destination path? E.g.

$ touch test
$ a=one
$ b=two
$ mv "test" "$a $b"
$ ls -la
total 8
-rw-r--r--  1 whitequark whitequark    0 2010-01-27 01:21  
-rw-r--r--  1 whitequark whitequark    0 2010-01-27 01:20   
drwxr-xr-x  2 whitequark whitequark 4096 2010-01-27 01:21 .
drwxr-xr-x 80 whitequark whitequark 4096 2010-01-27 01:16 ..
-rw-r--r--  1 whitequark whitequark    0 2010-01-27 01:21 one two
  • ah, using the move command instead of rename is a nice trick. I'll see if I can make that work in my script. – Torben Gundtofte-Bruun Jan 26 '10 at 22:34
  • 1
    rename is used for renaming stocks of files according to regular expression; it is not a standard way to rename files on *nix despite it's name nor even a standard tool: it is provided by Perl. See man rename for details. superuser.com/questions/70217/… is a question that is direct opposite for yours. Notice the first answer. – whitequark Jan 26 '10 at 22:38

If you're using bash, backslash-escape your spaces:

My\ File\ Name.jpg

  • So in a script that would be: rename $inputfile $date\ $time\ topic$ext ? I think I tried that and it just didn't rename but also didn't give an error. I'll try again and report back. – Torben Gundtofte-Bruun Jan 26 '10 at 22:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.