一道shell小测试题 及 答案
时间:2007-03-27 来源:bleach
写个脚本txtdel.sh,当运行后有下列运行结果:
无参数,扫描当前文件夹下所有.txt结尾的文件,列出前三行,提示是否要删除. $ ls food.txt
myprog.java
diary.txt
tempfile
story.txt $ txtdel.sh File: food.txt
Line 1: Chicken rice
Line 2: Hamburgers
Line 3: Curry
Delete? Y (user input)
File food.txt has been deleted. File: diary.txt
Line 1: Today I got up
Line 2: went to university
Line 3: and learned about UNIX!
Delete? N (user input)
File diary.txt was NOT deleted. File: story.txt
Line 1: It was a cold and stormy night…
Line 2: lots of rain…
Line 3: really quite awful…
Delete? Y (user input)
File story.txt has been deleted. No more .txt files to process. Finished! 答案: #!/bin/bash
for i in `find . -type f -name "*.txt"`
do
echo File: $i
head -n 3 $i |nl|sed 's/^ /Line /'|sed 's/Line../&:/'
echo -n "Delete? Y|N: "
read a
if [ $a == 'Y' ]
then
echo -n "really del $i, Y|N :"
read b
if [ $b == 'Y' ]
then
rm $i
echo "File $i has been deleted."
elif [ $b == 'N' ]
then
echo
echo "File $i was NOT deleted."
fi
elif [ $a == 'N' ]
then
echo " $i was NOT deleted."
fi
echo
done
无参数,扫描当前文件夹下所有.txt结尾的文件,列出前三行,提示是否要删除. $ ls food.txt
myprog.java
diary.txt
tempfile
story.txt $ txtdel.sh File: food.txt
Line 1: Chicken rice
Line 2: Hamburgers
Line 3: Curry
Delete? Y (user input)
File food.txt has been deleted. File: diary.txt
Line 1: Today I got up
Line 2: went to university
Line 3: and learned about UNIX!
Delete? N (user input)
File diary.txt was NOT deleted. File: story.txt
Line 1: It was a cold and stormy night…
Line 2: lots of rain…
Line 3: really quite awful…
Delete? Y (user input)
File story.txt has been deleted. No more .txt files to process. Finished! 答案: #!/bin/bash
for i in `find . -type f -name "*.txt"`
do
echo File: $i
head -n 3 $i |nl|sed 's/^ /Line /'|sed 's/Line../&:/'
echo -n "Delete? Y|N: "
read a
if [ $a == 'Y' ]
then
echo -n "really del $i, Y|N :"
read b
if [ $b == 'Y' ]
then
rm $i
echo "File $i has been deleted."
elif [ $b == 'N' ]
then
echo
echo "File $i was NOT deleted."
fi
elif [ $a == 'N' ]
then
echo " $i was NOT deleted."
fi
echo
done
相关阅读 更多 +