Bash 计算文件中10位数字的数量

Bash 计算文件中10位数字的数量,bash,grep,Bash,Grep,我需要计算一个文件中出现10位数字的实例总数。所有数字都有前导零,例如: This is some text. 0000000001 返回: 1 3 5 如果同一数字出现多次,则会再次计数,例如: 0000000001 This is some text. 0000000010 This is some more text. 0000000001 This is some other text. 返回: 1 3 5 有时数字之间没有空格,但每个连续的10位数字串都应计数: 000

我需要计算一个文件中出现10位数字的实例总数。所有数字都有前导零,例如:

This is some text. 0000000001
返回:

1
3
5
如果同一数字出现多次,则会再次计数,例如:

0000000001 This is some text.
0000000010 This is some more text.
0000000001 This is some other text.
返回:

1
3
5
有时数字之间没有空格,但每个连续的10位数字串都应计数:

00000000010000000010000000000100000000010000000001
返回:

1
3
5
如何确定文件中出现的10位数字的总数?

试试以下方法:

grep -o '[0-9]\{10\}' inputfilename | wc -l

最后一个要求——每行需要计算多个数字——不包括grep,据我所知,grep只能计算每行数字

编辑:显然,我被内特纠正了:)格雷普的
-o
选项正是我想要的

但是,您可以使用
sed
轻松做到这一点,如下所示:

$ cat mkt.sh 
sed -r -e 's/[^0-9]/./g' -e 's/[0-9]{10}/num /g' -e 's/[0-9.]//g' $1
$ for i in *.txt; do echo --- $i; cat $i; echo --- number count; ./mkt.sh $i|wc -w; done
--- 1.txt
This is some text. 0000000001

--- number count
1
--- 2.txt
0000000001 This is some text.
0000000010 This is some more text.
0000000001 This is some other text.

--- number count
3
--- 3.txt
00000000010000000010000000000100000000010000000001

--- number count
5
--- 4.txt
1 2 3 4 5 6 6 7 9 0
11 22 33 44 55 66 77 88 99 00
123456789 0

--- number count
0
--- 5.txt
1.2.3.4.123
1234567890.123-AbceCMA-5553///q/\1231231230
--- number count
2
$ 
“我需要计算文件中出现10位数字的实例总数。所有数字都有前导零”

所以我认为这可能更准确:

$ grep -o '0[0-9]\{9\}' filename | wc -l

这可能适合您:

cat <<! >test.txt
0000000001 This is some text.
0000000010 This is some more text.
0000000001 This is some other text.
00000000010000000010000000000100000000010000000001
1 a 2 b 3 c 4 d 5 e 6 f 7 g 8 h 9 i 0 j
12345 67890 12 34 56 78 90
!
sed 'y/X/ /;s/[0-9]\{10\}/\nX\n/g' test.txt | sed '/X/!d' | sed '$=;d'
8

cat Cool,不知道
-o
。为什么
{9\}
?这似乎没有在已经给出的答案上添加任何内容。由于
所有数字都有前导零
,因此我将第一个“0”数字分隔开,然后用此逻辑将剩余9位:)与
0,,,,,,,,,
将是一个10位数的数字,而
0123456789
不会。如果所有的数字都不是10位数呢?@potong那么它们将不符合规格,但它们可能会使用此解决方案,例如
'1234567890'
返回
'1'
@potong啊,很好的捕获,谢谢!已编辑,现在应该可以正常工作了。显然,内特的解决方案更受欢迎:)