parsing file names and then grouping similar files

Hello Friends,

I have .tar files which exists under different directories after the below code is run:

find . -name "*" -type f -print | grep .tar > tmp.txt
cat tmp.txt
./dir1/subdir1/subdir2/database-db1_28112009.tar
./dir2/subdir3/database-db2_28112009.tar
./dir3/application-app1_28112009.tar
./dir3/application-app2_21112009.tar
./dir4/application-app3_14112009.tar
./dir5/subdir4/ivr_backup-ivr1_21112009.tar
./dir6/subdir4/ivr_backup-ivr2_28112009.tar
.............

what i need is to group these .tar files under a spesific directory. I need to create a directory according to their descriptions like "database, application,etc" and place the related .tar files into this directories. If we consider "/" as delimeter i coudlnt parse the last part including file names. First i need to parse last parts with file name, then a second parsing in whole file name according to second delimeter "-" .

desired otput is

./database
db1_28112009.tar
db2_28112009.tar
./application
app1_28112009.tar
app2_21112009.tar
app3_14112009.tar
.....

Any help appreciated,

Change cp to mv if you want to move your files.

find . -name '*.tar' | 
  while IFS= read -r; do
    d=${REPLY##*/} d=${d%-*}
    [ -d ./"$d" ] || mkdir -- ./"$d" || exit 1
    cp -- "$REPLY" "./$d/${REPLY#*-}"
  done

If your read builtin doesn't support the -r option, just remove it.

cat tmp.txt | while read i;do
dir=${i%%-*}
if [ ! -d $dir ];then
mkdir $dir
fi
if [ ! -f $dir/$i ];then
cp $i $dir
fi
rm $i
done