find and replace using awk?

Hi, can some one let me know how I can use an awk script to be able to search every line in the file and find the state and zip code and insert a comma(,) between the state and zip fields. My file sample is shown below. Thanks for the  help.
john, doe, MO 78985
Mary, decker, TX 89989
Jason ,smith ,789 3r;st, NY 10009
charles, NY 10007

Open in new window

aej1973Asked:
Who is Participating?
 
ozoConnect With a Mentor Commented:
awk '{p=match($0,/[A-Z][A-Z] +[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]/);print substr($0,1,p+1) "," substr($0,p+2)}' file.txt
0
 
ozoCommented:
awk '{$NF=", " $NF; print}'
0
 
ozoCommented:
awk '$(NF-1)=$(NF-1) ","'
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
aej1973Author Commented:
I did not get you. is it

awk '$(NF-1)=$(NF-1) ","'' file.txt
0
 
ozoCommented:
yes
0
 
aej1973Author Commented:
ozo, this does not seem to be working. My actual data is as attached. The comma(,) is falling between the telephone number (ie) 317, 435-0000, but I need it to fall between state and zip (ie) TX , 66312-1111. Thanks for the help.

A
0900-005550 , 755;MORTIMER ST ,BAY,TX 66312-1111 , 317 435-0000
0900-005556 , 907;HULL ST ,BAY,IL 63312-1111 , 317 363-1000
0440-005559 , 620;PERRY ST ,NON PAY BACK BALANCE :BAR,MO 66312
0881-005552 , 350;ONE ST;APT 8 ,RAY,IL 63312 , 317 335-2456
0961-005551 , 1211;ROD ST ,RAY,IL 62312-1372 , 317 335-2400
0711-005553 , 438;BAINBRIDGE ST ,RAY,IL 62312-1098 , 317 335-0123

Open in new window

0
 
aej1973Author Commented:
ozo, you are the best! Thank you so much. Before I close this question can I ask you suggest a good reference manual /study guide for awk scripting that I can use. Thanks again.

a
0
 
ozoCommented:
0
 
omarfaridCommented:
good reference for awk:

http://www.grymoire.com/Unix/Awk.html
0
 
TintinCommented:
Another option is to use sed, eg:

sed "s/\(.*[A-Z]\)/\1,/" file.txt
0
 
aej1973Author Commented:
Awesome work, keep it up.

A
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.