Friday, 30 August 2013

Edit a phone list pattern using regex

Edit a phone list pattern using regex

I have just started reading about regex today and I have a question if
what i am trying to do below is possible?
I have a file containing phone numbers some are in (xxx) xxx-xxxx format
but some are in xxx-xxxx format.
so eg telephonelist:
(855) 422-6932
(899) 991-9054
(855) 912-7326
(833) 390-8072
934-2368
731-7056
251-5372
(855) 137-6285
(855) 294-5537
(844) 680-7479
so the objective is to add (000) in all of the lines that is not in (xxx)
xxx-xxxx format.
What i have worked out so far is basically to grep the output and write
them into a new file matching a regex pattern, and do another grep output
but this time not matching the regex and append it to the same file; as
below.
grep "([0-9]\{3\}) [0-9]\{3\}-[0-9]\{4\}" testfile > newtestfile ; grep -v
"([0-9]\{3\}) [0-9]\{3\}-[0-9]\{4\}" testfile | sed 's/^/(000) /' >>
newtestfile
But this will actually change the order of the list, as the new file becomes
(855) 422-6932
(899) 991-9054
(855) 912-7326
(833) 390-8072
(855) 137-6285
(855) 294-5537
(844) 680-7479
(000) 934-2368
(000) 731-7056
(000) 251-5372
Is there any way to do this without changing the order? I have been
researching using sed, awk and nl, but nothing so far. I am a noob..
Thanks for your help.

No comments:

Post a Comment