How can I grep for a regex containing multiple ranges with at least one occurence

巧了我就是萌 提交于 2021-02-16 21:42:31

问题


Given the following input I'm trying to grep for lines that begin with at least thee digits:

7.3M    ./user1
7.3M    ./user2
770M    ./user3
78M     ./user4
737M    ./user5
7.6M    ./user6

My grep command is not working:

grep ^[0-9]+[0-9]+[0-9]+M

I don't understand why unfortunately.


回答1:


Your regex, ^[0-9]+[0-9]+[0-9]+M, would match the start of string (^), then 1+ diigts (but it does not because + is not compatible with POSIX BRE that you are using since there is no -E nor -P options), then again 1+ digits two times and an M. If you used grep -E '^[0-9]+[0-9]+[0-9]+M', it would match strings like 123M.... or 12222234421112M.....

You may use the following POSIX BRE compatible regex:

grep '^[0-9]\{3\}'

Or a POSIX ERE compatible regex:

grep -E '^[0-9]{3}'

Details

  • ^ - start of a string/line
  • [0-9] - a digit from 0 to 9 (all ASCII digits)
  • \{3\} / {3} - BRE/ERE range quantifier requiring 3 occurrences of the quantified subpattern.

NOTE: On Sun OS, grep does not support range quantifiers, so you will have to use @FrankNeblung's suggestion there, spelled out pattern like ^[0-9][0-9][0-9]. It will also work with other tools that might not have full-fledge support for all regex quantifiers.



来源:https://stackoverflow.com/questions/46343657/how-can-i-grep-for-a-regex-containing-multiple-ranges-with-at-least-one-occurenc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!