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

Context :I've scanned a lot of old pictures, that have writing on the back.

Using imagemagick, I can append the front and back of the picture like this :

montage out20.jpg out21.jpg -gravity center -geometry +1+1 -tile 1x2 out2021.jpg; rm out20.jpg out21.jpg;
#(vertical append)

My problem is that I have a lot of pictures to apply the command on.

Is there a way to ask bash to apply "montage" to each odd file, adding automaticly the filename that comes after it ? The output filename is also a problem.

share|improve this question
up vote 4 down vote accepted

Quick and dirty:

ls *.jpg | while read file
  number=`echo $file | tr -dc 0-9`;
  if [ $((number % 2)) -eq 0 ]; then
    nextnumber=`echo $number + 1 | bc`;
    nextfile=`echo $file | sed s/$number/$nextnumber/`;
    outfile=`echo $file | sed s/$number/$number$nextnumber/`;
    montage $file $nextfile -gravity center -geometry +1+1 -tile 1x2 $outfile

You said to apply the montage to the odd files but provided even in your example. The code above will work for even. If you need the odd files to be first just change this line:

if [ $((number % 2)) -eq 0 ]; then

to be this:

if [ $((number % 2)) -eq 1 ]; then
share|improve this answer
Impressive and fast ! I'll try that – Manu Nov 3 '09 at 20:50
I don't know if every "left" image will be even or odd, all I'm sure of is that they follow each other... So, I could have out4.jpg out5.jpg out23.jpg out 24.jpg. – Manu Nov 3 '09 at 20:52
If that's the case then you can probably just remove the lines that start with "if" and "fi". – djhowell Nov 3 '09 at 20:59
Works great ! Thank very much. Now I have to tweak it, so that it'll take a file, append it to file+1, and then jump to file+2 .... – Manu Nov 3 '09 at 20:59
You can do something like nextfile=${file/$number/$nextnumber} instead of sed and you don't need bc for integer addition - just do ((nextnumber = number + 1)). – Dennis Williamson Nov 4 '09 at 5:44

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.