Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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:


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:

for f in /your/dir/*.JPG
  mv "$f" "${i}.jpg"

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
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
Parsing ls is evil. – 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
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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