打印每一行出现的数字个数
2021-03-16 19:41 jetwill 阅读(242) 评论(0) 编辑 收藏 举报题目描述
写一个 bash脚本以统计一个文本文件 nowcoder.txt中每一行出现的1,2,3,4,5数字个数并且要计算一下整个文档中一共出现了几个1,2,3,4,5数字数字总数。
示例:
假设 nowcoder.txt 内容如下:
a12b8
10ccc
2521abc
9asf
你的脚本应当输出:
line1 number: 2
line2 number: 1
line3 number: 4
line4 number: 0
sum is 7
说明:
不要担心你输出的空格以及换行的问题
方法一
num=1
sum=0
while read line
do
cnt=0
for((i=0;i<${#line};i++))
do
if [[ ${line:i:1} = '1' ]] || [[ ${line:i:1} = '2' ]] || [[ ${line:i:1} = '3' ]] || [[ ${line:i:1} = '4' ]] || [[ ${line:i:1} = '5' ]];then
cnt=$((cnt+1))
fi
done
echo "line${num} number: ${cnt}"
num=$((num+1))
sum=$((sum+cnt))
done < nowcoder.txt
echo "sum is ${sum}"
方法二
awk '
{
count=0;
len=length($0);
for(i=1;i<=len;i++)
{
s=substr($0,i,1)
if(0<s && s<6)
{
total++;
count++;
}
}
printf("line%d number:%d\n",NR,count);
}
END{ printf("sum is %d\n"),total}
' nowcoder.txt
方法三:
awk -F "" '{count=0;for(i=1;i<=NF;i++) {if($i>=1&&$i<=5) count++}sum+=count; print "line"NR" number:"count}END{print "sum is "sum}' nowcoder.txt
方法四:
awk 'BEGIN{sum=0}{
count = split($0,line,"");
line_sum=0
for(i=0;i<count;i++){
if(match(line[i],/[1-5]/)){
line_sum++;
sum++;
}
}
print "line"NR,"number:"line_sum;
}END{print "sum is",sum}'