shell字符串处理

字符串截取

  • 字符长度

    [user@host dir]$ str=123abc123
    [user@host dir]$ echo ${#str}
    9
    
  • 从左边截取
    ${string:position:length} :从字符串 string 的 position 位置截取 length 个字符串

    [user@host dir]$ str=123abc123
    [user@host dir]$ echo ${str:3:3} 
    abc
    [user@host dir]$ echo "${str:0:${#str}-3}"
    123abc
    
  • 从右边截取
    ${string:空格 -lenth} 截取字符串 string 的后 lenth 个位置

      #请注意 -4 前面的 空格符号
      [user@host dir]$ str=123abc123
      [user@host dir]$ echo ${str: -4}
      c123 
      #空格可以看成是 0
      [user@host dir]$ echo ${str:0-4}
      c123
      #1-4就相当于 空格-3 或者说 0-3
      [user@host dir]$ echo ${str:1-4}
      123
    

匹配删除

  • 从左匹配删除 # 和 ##
    ${string#mact_string}:从 string 左边开始匹配,删除匹配到的字符,尽可能少删除字符
    ${string##mact_string}:从 string 左边开始匹配,删除匹配到的字符,尽可能多删除字符
    其中 mact_string 可以是一个正则表达式

    [user@host dir]$ str=123abc123
    [user@host dir]$ echo "${str##*1}"
    23
    [user@host dir]$ echo "${str#*1}"
    23abc123
    [user@host dir]$ echo "${str##1}"
    23abc123
    [user@host dir]$ echo "${str#1}"
    23abc123
    
  • 从右匹配删除 % 和 %%

    [user@host dir]$ str=123abc123
    [user@host dir]$ echo ${str%%2*3}
    1
    [user@host dir]$ echo ${str%2*3}
    123abc1
    

匹配替换

  • 普通替换
    ${string/match_string/replace_string}:将 string 中第一个 match_string 替换成 replace_string
    ${string//match_string/replace_string}:将 string 中的 match_string 全部替换成 replace_string
    [user@host dir]$ str=123abc123
    [user@host dir]$ echo "${str/123/r}"
    rabc123
    [user@host dir]$ echo "${str//123/r}"
    rabcr
    
  • 前后缀替换
    ${string/#match_string/replace_string}:将 string 中第一个 match_string 替换成 replace_string
    ${string/%match_string/replace_string}:将 string 中的 match_string 全部替换成 replace_string
    [user@host dir]$ str=123abc123
    [user@host dir]$ echo "${str/#123/r}"
    rabc123
    [user@host dir]$ echo "${str/%123/r}"
    123abcr
    
  • 正则匹配
    match_string 可以是一个正则表达式
    [user@host dir]$ str=123abc123
    [user@host dir]$ echo "${str/3*1/r}"
    12r23
原文地址:https://www.cnblogs.com/igoodful/p/13055412.html