0

All,

OK! Trying to move image file to central images folder. Here is my script:

img_dir='/home/filies/images/'
img_fil='/home/files/img_dump.txt'
i='0'
while read -r fline
do
   fpath=$(dirname "$fline")"/"
   fname=$(basename "$fline")".$i"         
   nfile="$img_dir$fname"
   if [ ! -e "$nfile" ]; then
#      mv "$fline $img_dir$nfile"
      echo "NF=> $nfile"
   else
      ((i++))
#      mv "$fline $img_dir$nfile.$i"
      echo "F=> $fname P=> $fpath"
   fi 
done < ${img_fil}
exit

File moves currently commented out, till I get this right or have at least a likable result.

There are dups and my current script will not increment the counter for just the dupes of the same filename but for every dupe occurrence.

Is there a better way to do this and/or can I create a subroutine that does a search in the new image dir to find the latest increment number?

Cheers

OMR

1

You could do with a loop in your script:

nfile="$img_dir$fname"
while [ -e "$nfile" ]
do
  ((i++))
  fname=$(basename "$fline")".$i" 
  nfile="$img_dir$fname"
done

Now you have an unused filename

0

You can load them into an array with globbing and use the array size:

shopt -s nullglob
dups=("$nfile".*)
shopt -u nullglob
i=${#dups[@]}
((i++))

The numbering goes from 1 up, so when the file count is 0, you still need to increase it once to get 1. Setting nullglob is needed as otherwise the array size would be 1, as explained here: How to create a possibly empty array from filename glob?. shopt -u nullglob does the reverse, ie. it unsets the nullglob.

There's a gotcha here with other filenames fitting the pattern "$nfile".*. * will match anything, not just numbers, so be warned.

The whole would look like this:

img_dir='/home/filies/images/'
img_fil='/home/files/img_dump.txt'
#i='0'
while read -r fline
do
   fpath=$(dirname "$fline")"/"
   fname=$(basename "$fline")".$i"         
   nfile="$img_dir$fname"
   if [ ! -e "$nfile" ]; then
      mv "$fline $img_dir$nfile"
      echo "NF=> $nfile"
   else
      shopt -s nullglob
      dups=("$nfile".*)
      shopt -u nullglob
      i="${#dups[@]}"
      ((i++))
      mv "$fline $img_dir$nfile.$i"
      echo "F=> $fname.$i P=> $fpath"
   fi 
done < "${img_fil}"
exit 

Notice the line

i='0'

is commented out. Firstly, because in this situation it is not needed. Secondly, if you use another way of solving this, beware that the value of i would stay increased after each while loop if you don't reset it.

I added .$i for you in this line, so remove it if that's not what you want:

echo "F=> $fname.$i P=> $fpath" 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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