use "grep" command to find txt files containing telephone number

10,110

Solution 1

numbers are 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

Edit @Mark and Jed - good advice - made updates based off recommendations

Solution 2

$ 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
Share:
10,110
Josh Morrison
Author by

Josh Morrison

Updated on June 04, 2022

Comments

  • Josh Morrison
    Josh Morrison almost 2 years

    use "grep" command to find txt files containing telephone number.

    telephone number format could be:

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

    How to write it?