一、思路
1、第一个参数来判断脚本执行哪一个功能
-h 显示帮助信息
-c 统计文件 filename 中的 各个字母出现的次数
#echo"param1:$1";
if [ $1 ="-c"] ;then
统计文件 filename 中的 各个字母出现的次数
elif ["$1" = "-h" ] ;then
显示帮助信息
else
echo "no such param";
fi
2. 第二个参数是文件名称,默认是在当前目录下,我的测试文本是jiangxingqi
3.统计文件 filename 中的 各个字母出现的次数和概率
①将测试文件中的所有字母拆分,存储至t1,字母使用正则表达式来判断^[A-Za-z]+$
②对t1文件中的字母进行去重统计,存储至t2文件
sort t1 |uniq -c|sort -k1nr
③读取t2文件中字母所出现的次数,除以字母的总数即为字母出现的概率
p=`awk 'BEGIN{printf“%.2f%%\n",('$x'/'$cnt')*100}'`
二、shell
#echo "param1:$1";
p1="-c";
if [ $1 = $p1 ] ;then
file_content=$(cat $2);
rm -f t1;
touch t1;
# the number of alphabet in this file
cnt=0;
for line in "$file_content"; do
# count:the number of char in this line;
len=`echo $line|wc -m`
#echo $count $line
i=1;
# the index of alphabet in this line
while [ "$i" -lt "$len" ]; do
one_word=`echo $line|cut -c$i`
if [[ "$one_word" =~ ^[A-Za-z]+$ ]] ;then
#echo $i $one_word;
((cnt++))
echo "$one_word" >>t1;
fi
((i++))
done
done
#echo "the number of alphabet in this file is $cnt";
rm -f t2;
touch t2;
sort t1 |uniq -c|sort -k1nr > t2;
t2_content=$(cat "t2");
#echo $t2_content;
j=0;
OLD_IFS="$IFS"
IFS=" "
arr=($t2_content)
IFS="$OLD_IFS"
for x in ${arr[@]} ; do
b=$(( $j % 2 ))
if [ $b = 0 ] ; then
letter=${arr[j+1]}
p=`awk 'BEGIN{printf “%.2f%%\n",('$x'/'$cnt')*100}'`
echo $letter $x $p;
fi
((j++))
done
elif [ "$1" = "-h" ] ;then
echo "help infomation:"
echo "1.input command: ./wordcount.sh -c filename
function:count the number of character appear in this filename";
echo "2.input command: ./wordcount.sh -h
function:show the help infomation";
else
echo "no such param";
fi
三、运行结果
1. 显示help infomation
2.统计脚本执行结果