列表

详情


SHELL12. 打印每一行出现的数字个数

描述

写一个 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

说明:
不要担心你输出的空格以及换行的问题

原站题解

Bash 解法, 执行用时: 2ms, 内存消耗: 444KB, 提交时间: 2021-09-08

# awk -F"" 'BEGIN{sum=0} {count=0,for(i=1;i<=NF;i++){if($i ~ /[1-5]/){count++}} print "line"NR+1" number:"count,sum += count} END{print "sum is "sum}' nowcoder.txt
#!/bin/bash
row=0
sum=0
while read line
do
        num=0
        len=${#line}
        for((i=0;i<len;i++))
        do
                tmp=${line:i:1}
                if [[ ${tmp} -eq 1 || ${tmp} -eq 2 || ${tmp} -eq 3 || ${tmp} -eq 4 || ${tmp} -eq 5 ]]
                then
                        ((num++))
                fi
        done
        ((row++))
        ((sum+=num))
        echo "line${row} number:${num}"
done < nowcoder.txt
echo "sum is ${sum}"

Bash 解法, 执行用时: 3ms, 内存消耗: 376KB, 提交时间: 2021-07-17

#!/bin/bash
j=0
i=0
sum=0
while read line
do
    for((a=0;a<${#line};a++));do
        if [[ ${line:$a:1} =~ [1-5] ]];then
            i=$(($i+1))
        fi
    done
    j=$(($j+1))
    echo "line$j number:$i"
    sum=$(($sum+$i))
    i=0
done < nowcoder.txt
echo "sum is ${sum}"

Bash 解法, 执行用时: 3ms, 内存消耗: 376KB, 提交时间: 2021-05-10

linecount=0
sum=0
count=0

while read line
do
    for (( i=0; i<${#line};i++ ))
    do
        if [[  ${line:$i:1} =~ [1-5] ]]
        then
            count=$(($count+1))
        fi
    done
    linecount=$(($linecount+1))
    echo "line$linecount number:$count"
    sum=$(($sum+$count))
    count=0
    
done<nowcoder.txt
echo "sum is $sum"

Bash 解法, 执行用时: 3ms, 内存消耗: 376KB, 提交时间: 2021-05-03

#/bin/bash
linecount=0
sum=0
count=0

while read line
do
    for (( i=0; i<${#line};i++ ))
    do
        if [[  ${line:$i:1} =~ [1-5] ]]
        then
            count=$(($count+1))
        fi
    done
    linecount=$(($linecount+1))
    echo "line$linecount number:$count"
    sum=$(($sum+$count))
    count=0
    
done<nowcoder.txt
echo "sum is $sum"

Bash 解法, 执行用时: 3ms, 内存消耗: 412KB, 提交时间: 2022-01-05

#!/bin/bash

row=0
cut=0
while read line
do
	num=0
	sum=${#line}
	for((i=0;i<sum;i++))
	do
		tmp=${line:i:1}
		if [[ ${tmp} -eq 1 || ${tmp} -eq 2 || ${tmp} -eq 3 || ${tmp} -eq 4 || ${tmp} -eq 5 ]]
		then
	    	    ((num++))
	  	fi
	done
	((row++))
	((cut+=num))
	echo "line${row} number:${num}"
done < nowcoder.txt
echo "sum is ${cut}"

上一题