每天一道编程题(6)

1.  扫描当前目录下所有.txt结尾的文件,但每次列出10个文件,提示是否要删除这10个文件。若选择不是则不删除,并继续显示下10个文件询问提示。若选择是则删除,并继续显示下10个文件询问提示。

#!/bin/sh
PWD=/data0/test/
count=0
for i in `ls /data0/test/*.txt`
do
   ((count++));
   if [ $count -eq 10 ];then
        echo "$file" | sed -e 's/ /\n/g'
        read -p "Do you delete them or not?" c
        if ( c=="y" );then
                rm -rf $file
                count=0
                file=""
        fi
   else
       file=$file" "$i
   fi
done

    注意shell中的字符串连接为file=file" ""abc",if的判断可以使用c的判断。

     上面脚本有问题,可以看出来吗?在if判断式中,字符串判断中变量应该是字符串引用值$c,并且等号左右需要有空格"$c" = "y"或者"$c" == "y"。在test判断中,连续几个逻辑变量可以用-a或-o来表示。-a指and , o顾名思义指or。并且这里还有一个问题,当此目录下txt文件不足10时,也需要询问是否删除并展示。故最终的版本如下:

#!/bin/sh
PWD=/data0/test
count=0
num=0
sum=`find $PWD -name "*.txt" | wc -l`
if [ $sum -eq "0" ];then
   echo "There's no txt file in $PWD"
else
for i in `ls $PWD/*.txt`
do
   ((count++));
   ((num++));
   file=$file" "$i
   if [ $count -eq "10" -o $num -eq $sum ]; then
        echo "$file" | sed -e 's/ /\n/g'
        read -p "Do you delete them or not?" c
        if [ "$c" = "y" -o "$c" = "Y" ];then
                rm -rf $file
        fi
        count=0
        file=""
   fi
done
fi

   tip: find -name 中的名字需要有引号,比如find path -name "*.html",如无,结果是不对的。

猜你喜欢

转载自yeluowuhen.iteye.com/blog/2275327