Search code examples
shellgrepwc

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

Solution

  • 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