I am trying to copy and rename image files from one directory into another directory.

The files I want to copy have blank spaces embedded in their file names, and I want to replace part of the file name with the date that the image was taken.

Below is an example of the file names and the command that I have been using, along with an example of the error messages that I have been seeing.

For example, I would like to copy the "2008_08_17_Transfer 001.jpg" file from the source directory and rename it to "20090314001.jpg" in the target directory and so forth, for each file in the source directory that starts with "2008_08_17_Transfer ".

Here is what I tried and the error messages I see:

$ ls -l
total 241968
-rw------- 1 stephen stephen  1347770 Mar 14  2009 2008_08_17_Transfer 001.jpg
-rw------- 1 stephen stephen  1077919 Mar 14  2009 2008_08_17_Transfer 002.jpg
-rw------- 1 stephen stephen  1359947 Mar 14  2009 2008_08_17_Transfer 003.jpg
-rw------- 1 stephen stephen  1309175 Mar 14  2009 2008_08_17_Transfer 004.jpg
-rw------- 1 stephen stephen  1404298 Mar 14  2009 2008_08_17_Transfer 005.jpg

for i in *.jpg ; do scp -p "$i" /media/stephen/WDMyBook1_ext4/PicturesRenamedByDateTaken/2009/20090314/20090314`echo "$i" ` ; done

001.jpg: No such file or directory
002.jpg: No such file or directory
003.jpg: No such file or directory

2 Answers 2

for i in *.jpg ; do 
  cp -p "$i" "/media/stephen/WDMyBook1_ext4/PicturesRenamedByDateTaken/2009/20090314/20090314${i##* }"

The shell parameter expansion ${i##* } removes the longest prefix ending in a space (i.e. everything up to and including the space before the 00n.jpg numeric suffix). There is no need to use echo.

I'm assuming this is a local copy so you don't need scp.

Note: if you want to derive the 20090314 programmatically from the directory name, that's doable - but obviously complicates things a little.

  • This did EXACTLY what I wanted to do. Thank you so much!
    – user573739
    Nov 21, 2016 at 1:09

Just put quotes around the file name, like this

for i in *.jpg ; do scp -p "$i" "/media/stephen/WDMyBook1_ext4/PicturesRenamedByDateTaken/2009/20090314/20090314`echo "$i" `" ; done
  • This copied the files for me and added the date stamp on the front of the file name, but it also copied the entire file name, which is not what I wanted in this case. I do have a use for doing it this way, however, on some of my other directories, so this solution will also be useful to me. Thank you so very much.
    – user573739
    Nov 21, 2016 at 1:11

Your Answer

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