Sequentially rename multiple files

Hello team,

We wish to develop a script as follows :

  1. Rename multiple files in the following way:
    example
    Original file names : test.txt and dummy.txt
    New file names : test.$(date +"%F").AAAAA<serialno_1>.BBBBBB.p and dummy.$(date +"%F").AAAAA<serialno_2>.BBBBBB.p

  2. The script would run every hour where the serialno counter would continue from the count of the last run.

  3. The serialno counter would reset at 00:00:00 everyday.

  4. The files with the new filenames will be moved to a different location.

We have done the following implementation till now. However, I am finding it a little difficult given my limited knowledge of Linux shell scripting

This is just a test implementation :

 
for i in {1..5}
do
   mv *.txt test.$(date +"%F").AAAAA$i.111111.p
   echo "file renamed"
done
 

Could you please help.
Thanks,
Haider

Hello Haider,

Not tested though, could you please try following and let us know how it goes. Also make sure while setting this script to crontab you run it to 00:00 AM of your box time.

DATE_MIN=`date +%H%M`
if [[ ! -f count_file ]]
then
        count=1
else
        count=`cat count_file`
fi
if [[ $DATE_MIN == 0000 ]]
then
        count=1
fi
 
one=1
for i in *.txt
do
        DATE=`date +"%F"`
        mv $i "$i.$DATE<serialno_$count>.BBBBBB.p"
        if [[ $? == 0 ]]
        then
        count=`expr $count + $one`
        fi
done
echo $count > count_file

Also not sure what do you meant by point like files should move, question is when they should move at 12:00 AM ? or every hour ?

Thanks,
R. Singh

1 Like

There's a decision to take: starting the script once at midnight to run all day long sleeping most of the day or having cron start it on the quarter hour. The latter might be somewhat more dependable while the former would make the counter and date handling way easier.

If your script runs every hour, and the serialno resets at 00:00, then you can simply take the current hour as serialno.
The following is suitable for hourly crontab

ext=$(date +"%F").AAAAA$(date +"%H").BBBBBB.p

renamefile(){
newf=${1%.*}.$ext
test -f "$newf" || mv "$1" "$newf"
}

for i in *.txt
do
  test -f "$i" &&
  renamefile "$i"
done
1 Like