Linux Shell脚本:格式化手机号为xxx-xxxx-xxxx格式

在Linux系统中,我们经常需要对文本文件进行处理,例如格式化手机号。本篇文章将提供一个Shell脚本,可以将文本文件中的手机号转换成xxx-xxxx-xxxx的格式。

脚本代码

以下是一个示例的Shell脚本,名为format_phone.sh:shell#!/bin/bash

获取脚本输入的参数str=$1num=$2phone=$3

定义手机号格式化函数format_phone() { local phone=$1 local formatted_phone='${phone:0:3}-${phone:3:4}-${phone:7:4}' echo $formatted_phone}

对手机号进行格式化formatted_phone=$(format_phone $phone)

输出格式化后的结果echo '$str $num $formatted_phone'

使用方法

  1. 将上述代码保存为format_phone.sh文件。2. 在终端中使用chmod +x format_phone.sh命令赋予脚本执行权限。3. 运行脚本,例如:./format_phone.sh shs 20 13636568486

示例

输入:

shs 20 13636568486

输出:

shs 20 136-3656-8486

解释

  • 脚本首先获取输入的三个参数:strnumphone。* format_phone()函数接受一个手机号作为参数,使用字符串切片将其格式化为xxx-xxxx-xxxx的格式,并将结果返回。* 脚本调用format_phone()函数格式化输入的手机号。* 最后,脚本将格式化后的手机号与其他参数一起输出。

总结

这个简单的Shell脚本可以帮助你快速格式化文本文件中的手机号。你可以根据实际需求修改脚本,例如从文件中读取手机号或者将格式化后的结果保存到新的文件中。

Linux Shell脚本:格式化手机号为xxx-xxxx-xxxx格式

原文地址: https://www.cveoy.top/t/topic/Vb2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录