shell关于字符串处理完整脚本

一、处理字符串脚本

需求描述:
变量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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值