shell字符串的常用操作

版权声明:silly8543 https://blog.csdn.net/cen50958/article/details/89840287

 定义str变量,方便下面的操作演示
在这里插入图片描述

  • ${#string} 返回$string的长度

    [root@study ~]# echo ${#str}
    20

  • ${string:position} 在$string中,从位置position之后开始截取字符串

    [root@study ~]# echo ${str:4}
    is study string

  • ${string:position:length} 从$string指定位置开始截取长度为length字符串

    [root@study ~]# echo ${str:5:2}
    is

  • ${string#substring} 从$string开头开始删除最短匹配$substring字符串

    [root@study ~]# echo ${str#this}
    is study string

  • ${string##substring} 从$string开头开始删除最长匹配$substring字符串

    [root@study ~]# echo ${str##this}
    is study string

  • ${string%substring} 从$string结尾开始删除最短匹配$substring字符串

    [root@study ~]# echo ${str%ing}
    this is study str

  • ${string%substring} 从$string结尾开始删除最长匹配$substring字符串

    [root@study ~]# echo ${str%%ing}
    this is study str

  • ${string/substring/replace} 使用$replace来代替第一个匹配的$substring字符串

    [root@study ~]# echo ${str/is/AAA}
    thAAA is study string

  • ${string/#substring/replace} 如果$string前缀匹配$substring,就用 r e p l a c e replace来代替匹配 substring

    [root@study ~]# echo ${str/#th/AAA}
    AAAis is study string

  • ${string/#substring/replace} 如果$string后缀匹配$substring,就用 r e p l a c e replace来代替匹配 substring

    [root@study ~]# echo ${str/%ing/AAA}
    this is study strAAA

猜你喜欢

转载自blog.csdn.net/cen50958/article/details/89840287
今日推荐