使用命令行界面的文件中整数的数量 [英] Number of intergers in a file using Command Line Interface

查看:89
本文介绍了使用命令行界面的文件中整数的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用egrep计数文件中的整数数量?

How to count number of integers in a file using egrep?

我试图解决它作为模式发现问题.实际上,我面临的问题是如何连续表示字符[0-9] 的范围,这些字符的范围包括开头的空格"和结尾的空格或点".我认为后者可以通过使用\<和\>分别.另外,它之间不应包含点,否则将不是整数.我无法使用可用的工具和技术将此逻辑转换为正则表达式.

I tried to solve it as a pattern finding problem. Actually, I am facing problem of how to represent range of characters [0-9] continuously which include "space" before the beginning and "space or dot" after the end. I think the latter can be solved by using \< and \> respectively. Also, It should not include dot in between otherwise it will not be an integer. I am unable to convert this logic into regular expression using available tools and techniques.

My name is 2322.
33 is my sister.
I am blessed with a son named 55.
Why are you so 69. Is everything 33.
66.88 is not an integer
55whereareyou?

正确答案应该是5,即2322、33、55、69和33.

The right answer should be 5 i.e. for 2322, 33, 55, 69 and 33.

推荐答案

                    grep -Eo '(^| )([0-9]+[\.\?\=\:]?( |$))+' | wc -w
                          ^^    ^     ^       ^        ^   ^     ^
                          ||    |     |       |        |   |     |
E = extended regex--------+|    |     |       |        |   |     |
o = extract what found-----+    |     |       |        |   |     |
starts with new line or space---+     |       |        |   |     |
digits--------------------------------+       |        |   |     |
optional dot, question mark, etc.-------------+        |   |     |
ends with end line or space----------------------------+   |     |
repeat 1 time or more (to detect integers like "123 456")--+     |
count words------------------------------------------------------+


注意:123.123? 123:也算作整数


Note: 123. 123? 123: are also counted as integer

测试:

#!/bin/bash

exec 3<<EOF
My name is 2322.
33 is my sister.
I am blessed with a son named 55.
Why are you so 69. Is everything 33.
66.88 is not an integer
55whereareyou?
two integers 123 456.
how many tables in room 400? 50.
50? oh I thought it was 40.
23: It's late, 23:00 already
EOF

grep -Eo '(^| )([0-9]+[\.\?\=\:]?( |$))+' <&3 | \
  tee >(sleep 0.5; echo -n "integer counted: "; wc -w; )

输出:

 2322.
33 
 55.
 69. 
 33.
 123 456.
 400? 50.
50? 
 40.
23: 
integer counted: 12

这篇关于使用命令行界面的文件中整数的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆