Subscribe to Get Free Material Updates!
Visit my new blog WebData Scraping - Web Scraping Service provider company in India.

write a script to copy the file system from two directories to a new directory in such a way that only the latest file is copied in case there are common files in both the directories


clear
echo "Enter Directory 1:"
read dir1
echo "Enter Directory 2:"
read dir2
if [ ! -d $dir1 ] || [ ! -d $dir2 ]; then
 echo "dir1 not exist"
 exit 1
fi
`echo ls $dir1`>dir1.txt
`echo ls $dir2`>dir2.txt

echo "==============="

totalfile1=`wc -w dir1.txt|cut -c 8-9`  # HOME
totalfile2=`wc -w dir2.txt|cut -c 8-9`  # HOME
# totalfile1=`wc -w dir1.txt|cut -c 1-2`    # COLLEGE
# totalfile2=`wc -w dir2.txt|cut -c 1-2` # COLLEGE 
echo "totalfile:$totalfile1"
echo "totalfile:$totalfile2"


mkdir NEW_DIR
# copying all files from dir1 and comparing each file with files in dir2
i=$totalfile1
flag=0
while [ $i -ge 1 ] 
do
 file1=`tail -n $i dir1.txt | head -n 1`
 i=`expr $i - 1`
 flag=0
 j=$totalfile2

 while [ $j -ge 1 ] 
 do          
  file2=`tail -n $j dir2.txt | head -n 1`
  j=`expr $j - 1`          if [ "$file1" == "$file2" ];then
    flag=1
str1=`ls -l $dir1/$file1 | cut -d " " -c 50-55` 
# HOME
str2=`ls -l $dir2/$file2 | cut -d " " -c 50-55`  # HOME
# str1=`ls -l 3.sh|cut -d " " -f 7`     # COLLEGE
# str2=`ls -l 3a.sh|cut -d " " -f 7`    # COLLEGE

   hh1=`echo $str1 | cut -c 1-2`
   ss1=`echo $str1 | cut -c 4-5`
   hh2=`echo $str2 | cut -c 1-2`
   ss2=`echo $str2 | cut -c 4-5`

   # echo "hh1:$hh1 and ss1:$ss1";
   # echo "hh2:$hh2 and ss2:$ss2";
   if [ $hh1 -eq $hh2 ];then
    if [ $ss1 -le $ss2 ];then
     cp $dir2/$file2 NEW_DIR
    else
     cp $dir1/$file1 NEW_DIR
    fi
   else
    if [ $hh1 -le $hh2 ];then
     cp $dir2/$file2 NEW_DIR
    else
     cp $dir1/$file1 NEW_DIR
    fi
   fi
  fi
 done

 if [ $flag -eq 0 ];then
  cp $dir1/$file1 NEW_DIR
 fi
done

# copying remaining files that are in dir2 but not in 
dir1



i=$totalfile2
flag=0
while [ $i -ge 1 ] 
do
 file1=`tail -n $i dir2.txt | head -n 1`
 i=`expr $i - 1`
 flag=0
 j=$totalfile1






 while [ $j -ge 1 ] 
 do            
  file2=`tail -n $j dir1.txt | head -n 1`
  j=`expr $j - 1`        
  if [ "$file1" == "$file2" ];then
   flag=1
  fi
 done
 if [ $flag -eq 0 ];then
  cp $dir2/$file1 NEW_DIR
 fi
done


Output: 

1 comments:

Anonymous said...

output are differ then programming expectation :) its self modified

Post a Comment

Related Posts Plugin for WordPress, Blogger...

 
Design by Wordpress Theme | Bloggerized by Free Blogger Templates | coupon codes