Use the grep command to find txt files containing a phone number

use the grep command to search for txt files containing a phone number.

phone number format can be:

"***-*******"
"**********"
"*** *******"
"***-***-****"

How to write it down?

+3
source share
2 answers

digits - 3 digits (\ d {3}), space or dash [\ s-], 3 digits (\ d {3}), space or dash [\ s-], 4 digits (\ d {4}).

grep '\d{3}[\s\-]{0,1}\d{3}[\s\-]{0,1}\d{4}' infile.txt

Change @Mark and Jed - good advice - updates made based on recommendations

+6
source
$ cat file
test 1234567890 test
blah 123-4567890 junk junk 546-3345622 junk
blah blah 123 4575463 sdfsljads 123_456_4356 end
123--4567890

$ grep -Po '\d{3}[\s\-_]?\d{3}[\s\-_]?\d{4}'  file
1234567890
123-4567890
546-3345622
123 4575463
123_456_4356

$ ruby -ne 'puts $_.scan(/\d{3}[\s\-_]?\d{3}[\s\-_]?\d{4}/)' file
1234567890
123-4567890
546-3345622
123 4575463
123_456_4356
+2
source

Source: https://habr.com/ru/post/1795151/


All Articles