Structure Query Language, C programming, Java, Servlet, Jsp, Unix

Wednesday, 22 February 2012

Write a script to compare identically named files in two different directories and if they are same, copy one of them in a third directory.


[[  METHOD 1  ]]

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
i=$totalfile1
while [ $i -ge 1 ]
do
file1=`tail -n $i dir1.txt | head -n 1`
i=`expr $i - 1`
j=$totalfile2
while [ $j -ge 1 ]
do
file2=`tail -n $j dir2.txt | head -n 1`
j=`expr $j - 1`
if [ "$file1" == "$file2" ];then

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
done

[[  METHOD 2  ]]

echo "Enter dir1:"
read dir1
echo "Enter dir2:"
read dir2
if [ ! -d $dir1 ] || [ ! -d $dir2  ];then
echo "DIRECTORY NOT EXIST"
exit 1
fi
ls $dir1 > dir1.txt
ls $dir2 > dir2.txt
mkdir RESULT_DIR
for name1 in `cat dir1.txt`
do
for name2 in `cat dir2.txt`
do
if [ "$name1" == "$name2" ];then
record1=`ls -l $dir1/$name1`
record2=`ls -l $dir2/$name2`
time1=`echo $record1 | cut -d " " -f 8`
time2=`echo $record2 | cut -d " " -f 8`
HH1=`echo $time1|cut -d ":" -f 1`
SS1=`echo $time1|cut -d ":" -f 2`
HH2=`echo $time2|cut -d ":" -f 1`
SS2=`echo $time2|cut -d ":" -f 2`
if [ $HH1 -gt $HH2 ];then
cp $dir1/$name1 RESULT_DIR
elif [ $HH2 -gt $HH1 ];then
cp $dir2/$name2 RESULT_DIR
elif [ $SS1 -gt $SS2 ];then
cp $dir1/$name1 RESULT_DIR
elif [ $SS2 -gt $SS1 ];then
cp $dir2/$name2 RESULT_DIR
fi
fi
done
done


[[  METHOD 3  ]]

echo "Enter dir1:"
read dir1
echo "Enter dir2:"
read dir2
if [ ! -d $dir1 ] || [ ! -d $dir2  ];then
echo "DIRECTORY NOT EXIST"
exit 1
fi
ls $dir1 > dir1.txt
ls $dir2 > dir2.txt
mkdir RESULT_DIR
for name1 in `cat dir1.txt`
do
for name2 in `cat dir2.txt`
do
if [ "$name1" == "$name2" ];then
record=`ls -lt $dir1/$name1 $dir2/$name2 | head -n 1`
cpyfilename=`echo $record | cut -d " " -f 9`
`cp $cpyfilename RESULT_DIR`
fi
done
done

No comments:

Post a Comment