Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I'm working in CentOS with bash and I have files in a directory as follows:

16948.png 
16948_thumb.png
16948-1_thumb.png  
16949.png  
16948_thumb.png
16949-1_thumb.png 
16950-1.png  
16950-1_thumb.png
16950-2.png  
16950-2_thumb.png

I would like to do the following:

  • For each unique number N that exists in the list of files:
    • check that there is a file N-1.png:
    • if not, create it by copying N.png to N-1.png (there will always be an N.png)
    • delete the file N.png
    • check that there is a file N-1_thumb.png:
    • if not, create it by copying N_thumb.png to N-1_thumb.png (there will always be an N_thumb.png)
    • delete the file N_thumb.png.

However, my shell scripting isn't good enough to come close to this. This is as far as I've got - can anyone help?

#!/bin/sh

declare -a unique_numbers
for filename in ./images
do
  // split filename at - or _ to get N, and then check 
  // whether N is already in list of unique numbers
  // if it is, skip
  continue
  // if it isn't, append to unique_numbers
  unique_numbers+=(N)
  // then check whether there is a file N-1.png.. etc
done;
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

If I understand you well, this should do it. The first loop handles all files named Number.png and the second one handles all files named Number_thumb.png.

#!/bin/sh

for number in `ls -1 images/*.png | grep -v thumb | grep -v "-" | cut -f2 -d / | cut -f1 -d .`
do
  if [ ! -e "./images/$number-1.png" ] ; then
        cp images/"$number.png" images/"$number-1.png"
  fi
  rm ./images/"$number.png"
done;

for number in `ls -1 images/*.png | grep thumb | grep -v "-" | cut -f2 -d / | cut -f1 -d . | cut -f1 -d _`
do
  echo $number
  if [ ! -e "./images/$number-1_thumb.png" ] ; then
        cp images/"$number"_thumb.png images/"$number-1_thumb.png"
  fi
  rm ./images/"$number"_thumb.png
done;
share|improve this answer
    
Worked perfectly out of the box, lots of useful techniques in there. Thank you! –  Richard Jan 10 '12 at 12:41
add comment

Your Answer

 
discard

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.