问题
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 from0to9(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