Script to format phone numbers

Noob here, I need help with a shell script. I need to remove hyphens and add opening parenthesizes around the area code. I am able to show just the area code by adding echo {phone:0:3} to the script. Any help is much appreciated.

Write a script (called phone_num.sh) that prompts users for a phone number is this format xxx-xxx-xxxx

• convert it to (xxx) xxx-xxx

• convert it to xxxxxxxxx

Example If the input is 123-123-1234, your code would display

(123) 123-1234

1231231234

echo "Please enter phone number in the following format xxx-xxx-xxxx:"
read phone
echo ${phone:0:3}

This will give me the area code, which I'm not looking for. I need hyphens removed and parenthesizes added to the area code.

7

3 Answers

Maybe these variable assignments might help you out:

$ phonedash=123-123-1234
$ phonenodash="${phonedash//-}"
$ phone=$phonenodash
$ echo $phone
1231231234
$ echo "(${phone:0:3}) ${phone:3:3}-${phone:6:4}"
(123) 123-1234
$ new_phone=$(echo "(${phone:0:3}) ${phone:3:3}-${phone:6:4}")
$ echo $new_phone
(123) 123-1234
2

Bash + printf

$ VAR="123-456-7890"; printf "( %s ) %s - %s \n %s%s%s\n" ${VAR:0:3} ${VAR:4:3} ${VAR:8:4} ${VAR:0:3} ${VAR:4:3} ${VAR:8:4}
( 123 ) 456 - 7890 1234567890

sed

$ phone="123-456-7890"
$ plainPhone=$(echo $phone | sed "s/-//g")
$ formatedPhone1=$(echo $phone | sed "s/\(.*\)-\(.*\)-\(.*\)/(\1) \2 - \3/")
$ formatedPhone2=$(echo $plainPhone | sed "s/\([0-9]\{3\}\)\([0-9]\{3\}\)\([0-9]*\)/(\1) \2 - \3/")
$
$ echo $plainPhone
1234567890
$ echo $formatedPhone1
(123) 456 - 7890
$ echo $formatedPhone2
(123) 456 - 7890

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like