I'm writing a script that copies a set of files to a directory using bash scripting. A file that I'm trying to copy might already exist in the directory so I have to rename the file to avoid replacing the original one.
For an example if I have to copy a file called "abc.dd.java" and a file with the same name already exists, I have to rename the file as "abc.dd1.java" and copy it.
If the destination contains "abc.dd.java" and "abc.dd1.java" then the file should be renamed "abc.dd2.java"
I wrote a code snippet that does that:
#$file contains the full path for the original file.
#$path contains the full path for the copied file.
copypath="$path"
echo "$path"
count=1
while [ -f "$path" ]
do
part1=`echo "$copypath" | awk 'BEGIN{FS="."}{for(i=1;i<NF-1;i++){printf("%s.",$i)}printf("%s",$(NF-1))}END{}'`
part2=`echo "$copypath" | awk 'BEGIN{FS="."}{printf("%s",$NF)}END{}'`
path="$part1""$count.""$part2"
count=`expr "$count" + 1`
done
cp "$file" "$path"
This does work correctly. But it seems too crude. Isn't there a better way of separating out the file extension part and the name parts?
Thanks in advance