Filter and count the results at the same time with grep and wc

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

Upvotes: 1

Views: 328

Answers (2)

glenn jackman
glenn jackman

Reputation: 247022

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

Upvotes: 3

Krzysztof Czerwiński
Krzysztof Czerwiński

Reputation: 189

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

Upvotes: 2

Related Questions