It's working exactly as you've written it:
grep '[0-9]\{3,5\}' - Is there 3 to 5 sequential numeric characters in this string?
If the string is 1234567891234
, there is a sub-string in there that contains 3 - 5 numeric characters.
If you are only interested in strings that only contain 3 - 5 numeric characters and no more than 5 characters, you have to put some boundaries in your regular expression. You should also use the -E
flag which uses the more modern version of the regular expressions:
$ echo 12345678901234 | grep -E "(^|[^0-9])[0-9]{3,5}([^0-9]|$)"
This will not print anything, but this will:
$ echo 1234 | grep -E "(^|[^0-9])[0-9]{3,5}([^0-9]|$)"
And this:
$ echo 12345aaa6789aaa01234 | grep -E "(^|[^0-9])[0-9]{3,5}([^0-9]|$)"
The first (^|[^0-9])
says either at the beginning of the line (That's the leading ^
), or anything besides the characters 0-9. (That's the [^0-9]
). Using the (...|...)
in an extended regular expression means either the expression on the left or the expression on the right. The same goes for the ending ([^0-9]|$)
which says either non numerics or the end of a line.
In the middle is your [0-9]{3,5}
(no backslash needed for the extended expression). This says between 3 to 5 digits. And, since it is bound on either side by non-digits, or the beginning or end of the string, this will do what you want.
A couple of things:
$ echo 12345aaa6789aaa01234 | grep -E "(^|[^0-9])[0-9]{3,5}([^0-9]|$)"
and
$ grep -E "(^|[^0-9])[0-9]{3,5}([^0-9]|$)" <<<"12345aaa6789aaa01234"
Mean pretty much the same thing. However, the second is more efficient since only a single process has to run, and there's no piping. Plus, it's shorter to type.
Also, you can use (and it's preferred to use) character classes:
$ grep -E "(^|[^[[:digit:]])[[:digit:]]{3,5}([^[:digit:]]|$)"<<<"12345aaa6789aaa01234"
This will allow your regular expression to work even if you aren't in a place that uses Latin alphanumeric characters. This is a shorter way to do the same since \d
is the same class as [:digit:]
:
$ grep -E "(^|[^\d])\d{3,5}([^\d]|$)"<<<"12345aaa6789aaa01234"