Reputation: 9
I'm trying to show all phone numbers with two nonconsecutive "-" in it. I've tried these expressions:
grep '[-]{2}' phones.txt
grep '-{2}' phones.txt
grep '.*[-].+[-].+$' phones.txt
grep '^\d+[-]\d+[-]\d+$' phones.txt
But none are working. This is my first time using regular expressions and I'm not sure where I'm going wrong
Upvotes: 0
Views: 1215
Reputation: 11995
You could try something like:
grep '^.*-.*-.*$' phones.txt
This will find the case where the -
are adjacent and not. The -
can also be at the beginning or end.
If you're looking to restrict it to numbers like:
123-555-3456
ie. the -
are in the "middle" and separated by digits, you can use the more restrictive:
grep '[0-9]\+-[0-9]\+-[0-9]\+' phones.txt
For my sample phones.txt
:
012-345-678
012-345
012-345-
-012-345
012345
543838--499
--
1-2-3
the second pattern matches the following:
012-345-678
1-2-3
I'm using: grep (GNU grep) 2.4.2
Upvotes: 3
Reputation: 7385
Non consecutive or consecutive can be matched with (--?)
. This is a -
character followed by a -
which can exist zero or 1 times (optionally followed by).
Upvotes: 0