regex and grep match only string with only single or double digit
I need to extract a string with only single or double digit number in them. my file (test) looks like
test1correct
test12something
test123wrong
In t开发者_如何学Che above example, i want to grep only for test1correct and test12something
I tried this grep "test[0-9]{1,2}" test but it gives me all the 3 lines.
use: grep "test[0-9]{1,2}[^0-9]
"
Using lookaheads and lookbehinds you can specify "exactly one digit" or "exactly three digits" or whatever. This does exactly one digit:
echo 'WB123_4' | grep -Po '(?<![[:digit:]])([[:digit:]]{1})(?![[:digit:]])'
Result: 4
What it is doing is, find a digit that is not preceded by a digit, and also not followed by a digit. Also works for more than one digit. This does three digits, then at least one of anything else, then one digit:
echo 'WB123_4' | grep -Po '(?<![[:digit:]])([[:digit:]]{3})(?![[:digit:]]).+(?<![[:digit:]])([[:digit:]]{1})(?![[:digit:]])'
Result: 123_4
While I'm at it, this combination of grep and sed will find a string with three digits, then one or more of anything else, then one digit, and extract just those parts nicely. (There might have been another way to do that just in grep with groups.)
echo 'WB123_4' | grep -Po '(?<![[:digit:]])([[:digit:]]{3})(?![[:digit:]]).+(?<![[:digit:]])([[:digit:]]{1})(?![[:digit:]])' | sed -r -e 's/[^[:digit:]]+/ /'
Result: 123 4
Note: the -P flag to grep means to use Perl-style regular expressions, which lets you use lookaheads and lookbehinds.
Try this:
test[0-9]{1,2}[A-Za-z]+
cat tst--- tst file contains the following data 1 0 operator 4 5 5
cat tst | grep [0-9]--- while i grrp using using it return only 1
1
how to grep all the numbers in tst file?
精彩评论