Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

It's been a long time that I don't do any shell scripting.

I'm using Bash on a Ubuntu

I've a folder with many jpg pictures with some random name generated by the camera. I want to rename all pictures to create something like 1.jpg, 2.jpg, those sorted by date.

So far, I've ordered the pictures like this ls -alt which outputs this:

-rwxr-xr-x 1 pc-vell pc-vell 3919618 2013-04-29 13:28 P4295809.JPG
-rwxr-xr-x 1 pc-vell pc-vell 4293911 2013-04-29 14:15 P4295810.JPG
-rwxr-xr-x 1 pc-vell pc-vell 3819811 2013-04-29 14:27 P4295811.JPG
-rw-r--r-- 1 pc-vell pc-vell 4993078 2013-04-29 23:13 DSCF0880.JPG

So I must get P4295809.JPG and rename it to 1.JPG, and so on with the next ones.

I've cut the output to this:

DSCF1045.JPG
DSCF1046.JPG
DSCF1048.JPG
DSCF1050.JPG
DSCF1053.JPG
DSCF1054.JPG
DSCF1055.JPG

Using ls -altr | cut -c 55-100

But now I'm stuck. I don't know how to program a script from that...

Can you help me out? Thanks.

share|improve this question
    
You don't need cut to get only the name, just don't use l: ls -atr. – terdon May 7 '13 at 16:44
up vote 3 down vote accepted

You don't need to parse the ls output, just loop along what is found in the /your/dir/*.JPG expression.

This can work:

i=1
for f in /your/dir/*.JPG
do
  mv "$f" "${i}.jpg"
  i=$((i+1))
done

It will loop over the files matching *.JPG in /your/dir and rename them to counter.jpg.

share|improve this answer
    
well I had to parse the LS output, because I wanted it sorted by the modification date. But this worked like charm. Thanks!! – Reinherd May 7 '13 at 12:28
1  
Uhms, I see. In that case you could have used ls -1t (note 1 -one- not l -L-), that orders by time and just prints the names. – fedorqui May 7 '13 at 12:30
1  
Parsing ls is evil. mywiki.wooledge.org/ParsingLs – ignis May 7 '13 at 15:48
    
I know, I know (and also a little tired of everybody saying it :D). That's why I did not include it in my answer. – fedorqui May 7 '13 at 15:51
1  
We all know that parsing ls is evil for many reasons, but this script had to be ran just once, to rename bunch of files, which actually did the trick. I didn't want to have a professional and flawless script for ages, just a workaround. A programmer mind should understand that some answers, even if are not the best, are the most correct for that exact moment. – Reinherd May 8 '13 at 20:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .