Move file based on filename

Hi All

I need a script to manipulate files based on a filename:

example filename: 66600_042706.pdf

the script will create a directory 66000 only if this directory is not existing. If that directory is existing it will just move the file to 66000/666000_042706.pdf

in addition, i want to make sure that when moving the filename to the directory and there's an existing file with the same filename, it will add a random digit e.g. 66000/66000_042706_123.pdf

thanks

#!/bin/bash
FILE=66600_042706.pdf
DIR=${FILE%%_*}
if [ -d $DIR ]
then
    if [ -f $DIR/$FILE ]
    then
        NEWFILE=${FILE%.*}_$RANDOM.${FILE##*.}
    else
        NEWFILE=$FILE
    fi
else
    mkdir $DIR
fi
mv $FILE $DIR/$NEWFILE
filename="kamaraj_123.txt"
dir_name=`echo $filename | cut -d_ -f1`
echo $dir_name
if [ -d $dir_name ]; then
echo "there"
       if [ -f $dir_name\/$filename ]; then
        mv $filename $dir_name\/$file_name$RANDOM
    else
        mv $filename $dir_name\/$file_name
    fi
else
    mkdir $dir_name
    cp $filename $dir_name/
fi

awesome. thanks! Now how do i replace FILE to make it a variable knowing that the the filename convention is NNNNN_XXXX.pdf

also how do it do it when say the filename is 66000_INS.pdf
and i want this to be filed into 66000/INS/66000_INS.pdf

thanks again

FILE is a variable, i just initalized it at the beginning to have an example value.
Now you can :
Replace 1st line with FILE=$1, to have the ability to call the script like

./script 66600_042706.pdf

or put the code in a loop like :

for FILE in *.pdf
do
  .....
done

---------- Post updated at 10:21 ---------- Previous update was at 10:15 ----------

Second requirement :
Just replace

DIR=${FILE%%_*}

by

DIR=$(echo ${FILE%.*} | sed 's|_|/|g')