首页 > 解决方案 > Bash:如何提取字符串中所有“n”位数字的计数?

问题描述

我正在尝试使用 bash 从字符串中提取 n 位数字的总数。

例如,对于 3 位数字,

I am trying to extract 3 digited numbers 333, 334, 335 from this string #should return 3
I have 243 pens for sale #should return 1

不幸的是,我将无法使用sedor grepwith perl-regexp

感谢任何建议!

标签: regexbash

解决方案


您可以在 bash 中使用正则表达式。

#! /bin/bash
cat <<EOF |
I am trying to extract 3 digited numbers 333, 334, 335 from this string #should return 3, but should ignore 12345
I have 243 pens for sale #should return 1
123 should work at text boundaries, too 123
EOF
while read line ; do
    c=0
    while [[ $line =~ ([^[:digit:]]|^)([0-9][0-9][0-9])([^[:digit:]]|$) ]] ; do
        m=${BASH_REMATCH[0]}
        line=${line#*$m}
        ((++c))
    done
    echo $c
done

正则表达式解释:

([^[:digit:]]|^)([0-9][0-9][0-9])([^[:digit:]]|$)
~~~~~~~~~~~~~                                     non-digit
             ~~                                   or the very beginning
                 ~~~~~~~~~~~~~~~                  three digits
                                  ~~~~~~~~~~~~    non-digit
                                              ~~  or the very end

由于 bash 不能多次匹配同一个字符串,我们需要在尝试另一个匹配之前从字符串中删除已经处理的部分。


推荐阅读