View Full Version : Bash rename script

Saint Mike
22nd November 2006, 04:37 AM
Trying to rename a ton of files with spaces in there name to sequental numbers like

"this is my file 001.jpg" --> 001.jpg

In using the following

for f in *.jpg; do
mv `printf "this is my file %03d.jpg %03d.jpg" $num $num`
num=`expr $num + 1`

i trued just using "mv $f `printf "%03d.jpg" $num`"
and "mv \'$f\' `printf "%03d.jpg" $num`"

but im still getting mv: target `001.jpg' is not a directory .....ect ect ect

works fine going "mv this\ is\ my\ file\ 001.jpg oo1.jpg" or "mv 'this is my file 001.jpg' 001.jpg" manually but cant figure out why it dosnt like it :S

Changing move to echo it all comes out alright, i can copy past the lines of output and add mv to the start and they work fine.

I think the error is when you try move multiple files, it then requires a dir insted of a filename, cant see why it thinks im copying mult files though

any help would be great, or another easier way to do this :)

22nd November 2006, 05:02 AM
Did you try and

cd this\is\my\file\001.jpg

and then try it? Seems to work when I CD the directory on my end.

Saint Mike
22nd November 2006, 06:22 AM
Dont quite understand you, i tried
cd tothedirectory
as the start to make sure its in right directory, but it should be anyway.

My problem is the spaces in the file names.
I tried making some files like asd001.jpg and they work fine, i cant get it to work with spaces though.

The filenames are eg "My photoe collection 001.jpg", mv keeps thinking im trying to move multi files into one directory, i cant get it to see the filename with spaces are one item. its trying to copy My, Photo, collection, 001.jpg into a directory 001.jpg

22nd November 2006, 06:33 AM
Do you just want to drop the 'this is my file' part and keep the rest of the file name?

Or do you want to convert all files to a sequential order like this:

this is my file 001.jpg --> 001.jpg
this is my file 004.jpg --> 002.jpg
this is my file 010.jpg --> 003.jpg

22nd November 2006, 06:43 AM
If the file names are all the same you could use a script like this to strip the "My photo collection " prefix.

for i in *.jpg; do
tmp=${i##My*collection }
mv "$i" "$tmp"

Saint Mike
22nd November 2006, 06:43 AM
Thx guys got it to work, just needed " quotes

for f in *.jpg; do
mv "$f" `printf "%03d.jpg" $num`
num=`expr $num + 1`

Saint Mike
22nd November 2006, 06:45 AM
beat me too it pwiesen, Thx :)

It just needed "$f", i was trying '$f' which it didnt like "S

22nd November 2006, 07:12 PM
Those quote things can be a pain.

Glad you got it working.