Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to separate a 10-digit phone number into two parts

Tags:

ksh

sed

For example, I get a phone number like 9191234567, how could I separate it into two parts, with the first part containing the three leading digits 919 and the other part containing the rest seven digits 1234567? After that, I want to store these two parts into two different variables in ksh.

I don't know if this could be done with sed?

like image 380
Qiang Xu Avatar asked Dec 05 '22 10:12

Qiang Xu


2 Answers

You could try this :

echo "9191234567" | sed 's/^\([0-9]\{3\}\)\([0-9]\{7\}\)$/\1 \2/'

To store each part in a separate variable, you could do this :

phone="9191234567"
part1=$(echo $phone | sed 's/^\([0-9]\{3\}\)[0-9]\{7\}$/\1/')
part2=$(echo $phone | sed 's/^[0-9]\{3\}\([0-9]\{7\}\)$/\1/')

Or even more concise :

read part1 part2 <<< $(echo "9191234567" | sed 's/^\([0-9]\{3\}\)\([0-9]\{7\}\)$/\1 \2/')
like image 53
Eric Citaire Avatar answered Mar 03 '23 19:03

Eric Citaire


cut should work

echo '9191234567' | cut --characters 1-3,4- --output-delimiter ' '
919 1234567
like image 23
iruvar Avatar answered Mar 03 '23 17:03

iruvar