Register
It is currently Sat Oct 25, 2014 4:48 pm

Insert file with number into existing sequencial file set


All times are UTC - 6 hours


Post new topic Reply to topic  [ 1 post ] 
Author Message
 PostPosted: Thu Mar 11, 2010 3:26 am   

Joined: Thu Mar 11, 2010 3:18 am
Posts: 1
Hi!

I wanted to share a script I wrote originally to insert a forgotten photo into a sequencial image set (01image1.jpg, 02image2.jpg, ...).
If index is already used, it shifts all later files in the sequence, and then introduces the new file.
Code:
# Script to insert a filename into a sequenced file set.
# It updates numerotation if given number already present into the sequence.
# Usage: insertphoto.sh [distdir] [-nXX] filetomove filename
#   will move filetomove to [distdir/]XXfilename.ext (ext is extracted from given filetomove)
if [ -d "$1" ];
then
   distdir="$1";
   shift
else
   distdir=`pwd`;
fi

IFS=$'\n'
insno=00;
while [ -n "$1" ]; do
   if [[ "$1" =~ -n[0-9]+ ]];
   then
      insno=`printf "%02d" ${1:2}`;
   else
      if [ -f "$1" ];
      then
         filetomove="$1";
         basetomove=`basename "$filetomove"`;
         doexist=`ls -1 "$distdir/$insno"* 2>/dev/null`;
         # renumerate if number already in sequence
         if [ -n "$doexist" ];
         then
            for i in $(ls -1 "$distdir/"[0-9]* 2>/dev/null); do
               filename=`basename "$i"`
               numi=`expr "$filename" : "\([0-9][0-9]*\)"`;
               if [[ "$numi" -ge "$insno" && "$filename" != "$basetomove" ]];
               then
                  ((numi+=1));
                  numi=`printf %02d $numi`;
                  mv "$i" "$distdir/$numi${filename:2}";
               fi
            done
         fi
         # no given number: look for biggest, and increment it
         if [ $insno -eq 0 ];
         then
            lsarr=($(ls -1 "$distdir/"[0-9]* 2>/dev/null));
            lenarr=${#lsarr[*]};
            if [ "$lenarr" -ne "0" ];
            then
               ((lenarr-=1));
               lastfile="${lsarr[lenarr]}";
               insno=`expr "$lastfile" : "\([0-9][0-9]*\)"`;
               ((insno+=1));
               insno=`printf "%02d" $insno`;
            else
               shift;
               break;
            fi
         fi
         shift;
         # inserting file
         mv "$filetomove" "$distdir/$insno$1.${basetomove##*.}";
      fi
   fi
   shift;
done

It is maybe useful to somebody...
Take care!


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP