How to split a 10-digit phone number into two parts

For example, I get a phone number, for example 9191234567 , how can I divide it into two parts, with the first part containing three leading digits 919 , and the other part containing the remaining seven digits 1234567 ? After that, I want to save these two parts in two different variables in ksh .

I don’t know if this can be done with sed ?

+4
source share
5 answers

You can try the following:

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

To save each part in a separate variable, you can 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/') 
+7
source

cut should work

 echo '9191234567' | cut --characters 1-3,4- --output-delimiter ' ' 919 1234567 
+4
source
 echo 9191234567 | sed 's/^\([1-9]\{3\}\)\([1-9]*\)/\1\-\2/' 

Will be printed 919-1234567

+2
source

Using bash

 $ phone=9191234567 $ regex="^([0-9]{3})([0-9]{7})$" $ [[ $phone =~ $regex ]] && part1="${BASH_REMATCH[1]}" && part2="${BASH_REMATCH[2]}" $ echo $part1 919 $ echo $part2 1234567 
+2
source

Pure ksh, take a number, type as two separate lines, separated by a space.

 function split_at_third { typeset number=$1 ab b=${number#???} && a=${number%$b} print $a $b } 
0
source

Source: https://habr.com/ru/post/1483662/


All Articles