I am trying to write a script that uses sed and takes takes a text file containing phone numbers with area code 301 followed by 209( 3012093934, (301) 2093935, (301)209-3936 ). I have to remove the blank, dash, parenthesis where they separate the area code and the number. Then I have to write the correct numbers to another file; the correct numbers meaning the ones that start by area code 301, followed by 209 and exactly 4 more digits.

So my regular expression is this but doesn't seem to work correctly:

sed -n 's/(^301[\- ]*)/(209)/([0-9][0-9][0-9][0-9]$\)/p'

Can somebody help? Thanks in advance!!!


remove all characters that are not a digit, and then remove lines that do not start as desired, finally remove those that are not 10 characters:

sed -e 's/[^0-9]//g' -e '/^301209/!d' -e '/^.\{10\}$/!d'

I would start off by removing the undesirable characters with tr and then filter with grep:

tr -d '() -'|grep '301209[0-9][0-9][0-9][0-9]$'
  • @don_crissti There are no square brackets either: just tr -d '() -'
    – xhienne
    Jan 13 '17 at 20:39
  • I came up with this change after failing with tr -d '() -'. You are right though, the problem is not related to the unneeded brackets. Jan 13 '17 at 20:56
  • jp - hot or cold?
    – mikeserv
    Jan 18 '17 at 14:15
sed -n 's/.*\(301\).*\(209\).*\([0-9]\{4\}\)/\1\2\3/w foobar'

This removes all the characters before 301 (to account for (309)), and zero or more occurrences of space and ) after 301 with exactly four digits after 209 ignoring any non-digit characters. The output is written to foobar.

sed -ne '/^ *\(+1\)\{0,1\} *(\{0,1\} *301 *)\{0,1\} *209 *-\{0,1\}\( *[0-9]\)\{4\} *$/s/[^0-9]*//gp'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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