遍历文件每一行,具体差异主要在针对每一行的处理流程:

1.将单行所有字符单独获取在处理*(solution1,solution2,solution4,solution5) / 正则处理清除其他字符只留下目标数字(solution3)
2.单个字符正则匹配,awk形式, if [[ =~ ]] 形式

#!/usr/bin/env bash

function solution1() {
    local line_num=0
    local sum=0
    local temp=""
    local digit_num=0
    while read line; do
        ((line_num++))
        digit_num=`echo "${line}" | awk -F "" '{for (i=1;i<=NF;i++) { if($i ~ /[1-5]/) {printf $i;} }}' | awk '{print length($0)}'`
        if [ -z "${digit_num}" ];then
            digit_num=0 
        fi
        echo "line${line_num} number:${digit_num}"
        sum=$((${sum} + ${digit_num}))
        #sum=`expr ${sum} + ${digit_num}`
    done < nowcoder.txt
    echo "sum is ${sum}"
}

function solution2() {
    local line_num=0
    local sum=0
    local temp=""
    local digit_num=0
    while read line; do
        temp=`echo "${line}" | awk -F "" '{for (i=1;i<=NF;i++) { if($i ~ /[1-5]/) {printf $i;} }}'`
        digit_num=${#temp}
        sum=$((${sum} + ${digit_num}))
        ((line_num++))
        echo "line${line_num} number:${digit_num}"
    done < nowcoder.txt
    echo "sum is ${sum}"
}

function solution3() {
    local line_num=0
    local sum=0
    local temp=""
    local digit_num=0
    while read line; do
        #temp=`echo "${line}" | sed 's/[a-z]\|[A-Z]\|[6-9]\|0//g'`
        temp=`echo "${line}" | sed 's/[^1-5]//g'`
        digit_num=${#temp}
        sum=$((${sum} + ${digit_num}))
        ((line_num++))
        echo "line${line_num} number:${digit_num}"
    done < nowcoder.txt
    echo "sum is ${sum}"
}

function solution5() {
    local line_num=0
    local sum=0
    local temp=""
    #while read line; do
    for line in `cat nowcoder.txt`; do
        local digit_num=0
        for (( i=0; i<${#line}; i++ )); do
            temp=${line:${i}:1}
            if [[ "${temp}" =~ ^[1-5]+$ ]]; then
                ((digit_num++))
            fi
        done
        sum=$((${sum} + ${digit_num}))
        ((line_num++))
        echo "line${line_num} number:${digit_num}"
    done < nowcoder.txt
    echo "sum is ${sum}"
}

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