导航:[首页]->[bash]->[Bash学习-字符串操作]

字符串长度

    str="abcdefg"
    # 计算长度
    echo "str:${str},length ${#str}" # str:abcdefg,length 7
    echo "length `expr length $str`"
    str="abde"
    echo "str:${str},length ${#str}" # str:abde,length 4

提取字串

    str="abcdefg"
    # 从第二个字符到结尾
    echo "${str:1}" # bcdefg
    # 从第三个字符开始截取2个字符
    echo "${str:2:2}" # cd

    # 从倒数第二个字符到结尾
    echo "${str:(-2)}" # fg
    # 注意:后面的空格
    echo "${str: -2}" # fg
    echo "${str:(-2):1}" # f

子串削除

  • ${string#substring} 从$string的开头位置截掉最短匹配的$substring.
  • ${string##substring} 从$string的开头位置截掉最长匹配的$substring.
  • ${string%substring} 从$string的结尾位置截掉最短匹配的$substring.
  • ${string%%substring} 从$string的结尾位置截掉最长匹配的$substring. declare var="abc/def/ghi" echo "${var}" echo ${var#/} # def/ghi echo "${var##/}" # ghi echo "${var%/}" # abc/def echo "${var%%/}" # abc

字串替换

  • ${string/substring/replacement} 使用$replacement来替换第一个匹配的$substring.
  • ${string//substring/replacement} 使用$replacement来替换所有匹配的$substring.
  • ${string/#substring/replacement} 如果$substring匹配$string的开头部分, 那么就用$replacement来替换$substring.
  • ${string/%substring/replacement} 如果$substring匹配$string的结尾部分, 那么就用$replacement来替换$substring. declare var="abc/def/ghi/abc" # 替换普通字符 echo "${var/b/c}" # acc/def/ghi/abc echo "${var//b/c}" # acc/def/ghi/acc

      # 替换特殊字符
      echo "${var//\//\\}" # abc\def\ghi\abc
      var="abc\def\ghi\abc"
      # 注意后面的/没有用转义
      echo "${var//\\//}" # abc/def/ghi/abc
    

字符串查找

匹配字符
  • expr index $string $substring 在字符串$string中所匹配到的$substring中任意字符第一次所出现的位置. declare var="abc/def/ghi/abc" echo expr index $var def # 5 echo expr index $var /g # 4 echo expr index $var fjdaf # 1
    查找
  • expr match "$string" '$substring' $substring是一个正则表达式.
  • expr "$string" : '$substring' $substring是一个正则表达式.declare var="abc/def/ghi/abc" # StartWith echo expr match $var "abc" # 3 echo expr match $var "ghi" # 0

      # EndWith
      echo `expr match $var ".*abc$"` # 15
      echo `expr match $var ".*abcd$"` # 0
    
      # Find
      echo `expr match $var ".*ghi"` # 11
    

参考