1

My project It's to filter phone numbers in a list where is so many things inside. So I want to display the phone number I already filter, with the number of line which corresponding to the number of phone numbers. I filter american phone numbers only american phone numbers. And the rule it is to use pipe |.

   grep  "^([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$" $1 | wc -l  > result-phonenumber-filter.txt 

The data.txt which contains numbers we need to filter :

      (512) 258-6589

    (205) 251-6584

    (480) 589-9856

    (303) 548-9874

    (808) 547-3215

    (270) 987-6547

    (225) 258-9887

    (314) 225-2543

    (979) 547-6854

    (276) 225-6985

    les numeros suivants ne sont pas valables pour ce programme :

    +512 325

+512 251 2545654654

+512 6546 6464646

+512546546646564646463313

(314) sgf225-2543

(314) 225-2543fsgaf

(314afd) 225-2543

FSd(314) 225-2543

The result I want to obtain is :

(512) 258-6589
(205) 251-6584
(480) 589-9856
(303) 548-9874
(808) 547-3215
(270) 987-6547
(225) 258-9887
(314) 225-2543
(979) 547-6854
(276) 225-6985

The number of line is :10

2 Answers 2

3

This is needlessly tricky, but it works without creating any temp files. Requires bash for the process substitution

grep -oP '^\s*\(\d{3}\) \d{3}-\d{4}\s*$' file | tee >(echo "there are $(wc -l) matches")

I'd go with awk or perl

perl -ne '
    if (/^\s*\(\d{3}\) \d{3}-\d{4}\s*$/) {print; $count++} 
    END {print "there are $count matches\n"}
' file
awk '
    /^[[:blank:]]*\([[:digit:]]{3}\) [[:digit:]]{3}-[[:digit:]]{4}[[:blank:]]*$/ {print; count++} 
    END {print "there are", count, "matches"}
' file
1
2
grep -E '^[ ]{0,9}\([0-9]{3}\) [0-9]{3}-[0-9]{4}[ ]{0,9}$' data.txt | sed 's/^[ \t]*//' > result-phonenumber-filter.txt
count=$(wc -l result-phonenumber-filter.txt)
echo "The number of line is :$count" >> result-phonenumber-filter.txt
$ cat result-phonenumber-filter.txt
(512) 258-6589
(205) 251-6584
(480) 589-9856
(303) 548-9874
(808) 547-3215
(270) 987-6547
(225) 258-9887
(314) 225-2543
(979) 547-6854
(276) 225-6985
The number of line is :10
2
  • 's/^[ \t]*//' can you just explain this part please? I tried to understand alone but I think I don't really understand what append here.. Oct 2, 2018 at 14:30
  • 1
    It removes spaces and tabs at the start of the line, try to run it without the sed part and You should understand it. Oct 2, 2018 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.