格式化电话号码的脚本

格式化电话号码的脚本

我是菜鸟,我需要 shell 脚本方面的帮助。我需要删除连字符并在区号周围添加左括号。我可以通过向脚本添加 echo {phone:0:3} 来仅显示区号。任何帮助都非常感谢。

编写一个脚本(名为 phone_num.sh),提示用户输入电话号码,格式为 xxx-xxx-xxxx

• 将其转换为 (xxx) xxx-xxx

• 将其转换为 xxxxxxxxx

例如,如果输入的是 123-123-1234,则代码​​将显示

(123) 123-1234

1231231234

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

这将给出我不需要的区号。我需要删除连字符并在区号中添加括号。

答案1

也许这些变量分配可能会帮助你:

$ 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

答案3

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

相关内容