一、处理字符串脚本
需求描述:
变量str=“shell is a handsome language,the handsome language is shell”,执行脚本后,打印输出str字符串变量,并给出用户选项:
1、打印str长度
2、删除字符串中所有的handsome
3、替换第一个 language为program
4、替换全部 language为program
用户输入数字1、2、3、4,可以执行对应的功能;输入q or Q 退出交互模式
二、思路分析
1、将不同的功能模块进行划分,并编写函数
function output_str
function len_str
function del_handsome
function rep_language_one
function rep_language_all
2、实现第一步定义的功能函数
str="shell is a handsome language,the handsome "
function output
{
echo "1、打印str长度"
echo "2、删除字符串中所有的handsome"
echo "3、替换第一个 language为program"
echo "4、替换全部 language为program"
}
function len_str
{
echo "${#str}"
}
function del_handsome
{
echo "${str#handsome}"
}
function rep_language_one
{
echo "${str/language/program}"
}
function rep_laguage_all
{
echo "${str//language/program}"
}
3、程序主流程的设计
while true
do
echo "【str=$str】"
echo
output
read -p "please input your chioce(1\2\3\4\q\Q):" choice
case $choice in
1)
len_str
;;
2)
del_handsome
;;
3)
rep_language_one
;;
4)
rep_language_all
;;
q|Q)
exit
;;
*)
echo "输入有误,请重新输入"
esac
done
三、完整脚本设计
代码如下(示例):
!/bin/bash
str="shell is a handsome language,the handsome "
function output
{
echo "1、打印str长度"
echo "2、删除字符串中所有的handsome"
echo "3、替换第一个 language为program"
echo "4、替换全部 language为program"
}
function len_str
{
echo "${#str}"
}
function del_handsome
{
echo "${str#handsome}"
}
function rep_language_one
{
echo "${str/language/program}"
}
function rep_laguage_all
{
echo "${str//language/program}"
}
while true
do
echo "【str=$str】"
echo
output
read -p "please input your chioce(1\2\3\4\q\Q):" choice
case $choice in
1)
len_str
;;
2)
del_handsome
;;
3)
rep_language_one
;;
4)
rep_language_all
;;
q|Q)
exit
;;
*)
echo "输入有误,请重新输入"
esac
done