1

I am attempting to parse out a telephone number column from a file data.

XiaoLi,lxiao,lxiao@unc.edu,6705462234,Jackson,NC764
NatkinWilliam,wnatkin,wnatkin@vcu.edu,8044344528,Salem,VA22345
EliziMoe,emoe,emoe@ncsu.edu,5208534566,Tempe,AZ85282
MaTa,mta,mta@yahoo.com,4345667345,Austin,TX91030
DianaCheng,dcheng,dcheng@asu.edu,5203456789,Matitsi,WY4587
JacksonFive,jfive,jfive@ncsu.edu,5206564573,Kyenta,AZ85483
AdiSrikanthReddy,sadi1,sadi1@asu.edu,6578904566,Wyo,WS67854

I am writing a script that will take the phone number and reorganize it. I have been able to isolate the phone number column with

phonm=`awk -F, '{ print $4 }' data3`

when used by itself, I get the output

6705462234
8044344528
5208534566
4345667345
5203456789
5206564573
6578904566

The problem is that I need to format these numbers in the format ###-###-####

So I used the command

echo "${phonm:0:3}-${phonm:3:3}-${phonm:6:4}"

When I run this, I do the the desired result. But it will only print/format the first line.

670-546-2234

How do I make this command iterate down the column?

4

Simply tell awk to print the portions of the string, separated by the hypens:

awk -F, '{print substr($4,1,3) "-" substr($4,4,3) "-" substr($4,7,4)}' < data3

Sample output:

670-546-2234
804-434-4528
520-853-4566
434-566-7345
520-345-6789
520-656-4573
657-890-4566

The reason that you got the output you did was that you saved all of awk's output into a shell variable, then asked for the specific portions of that string. The variable itself had embedded newlines in it, and contained all of the phone numbers, you just would have had to loop through them all by hand, or just have awk do it.

$ echo "$phonm" |od -c
0000000   6   7   0   5   4   6   2   2   3   4  \n   8   0   4   4   3
0000020   4   4   5   2   8  \n   5   2   0   8   5   3   4   5   6   6
0000040  \n   4   3   4   5   6   6   7   3   4   5  \n   5   2   0   3
0000060   4   5   6   7   8   9  \n   5   2   0   6   5   6   4   5   7
0000100   3  \n   6   5   7   8   9   0   4   5   6   6  \n
0000115
  • Thank you so much for the explanation. It has really helped me out. I am still a bit new to awk so this insight is exactly what I was looking for! – Ububtunoob Oct 31 '17 at 0:14
0

Here's Perl.

perl -F, -anE'$F[3] =~ /(\d{3})(\d{3})(\d{4})/; say "$1-$2-$3"' data3

-F tells Perl to split each line on commas

-anE tells Perl to put lines into an array (a); to run process each line (n), and to execute the code that follows using Perl 5.10

$F[3] is the desired column

Then it captures three digit groups by regex matching of $F[3]. And finally it prints them to STDOUT with minuses in between.

data3 is the input file.

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.