Linux shell字符串截取、替换、删除以及trim

  1. 字符串截取

    • 从左向右截取第一个//后的字符串

      word=abcd-//master-01://httpab
      echo ${word#*//} 
      # 输出:master-01://httpab
      
    • 从左向右截取最后一个//后的字符串

      word=abcd-//master-01://httpab
      echo ${word##*//} 
      # 输出:httpab
      
    • 从右向左截取第一个//后的字符串

      word=abcd-//master-01://httpab
      echo ${word%//*} 
      # 输出:abcd-//master-01:
      
    • 从右向左截取最一个//后的字符串

      word=abcd-//master-01://httpab
      echo ${word%%//*} 
      # 输出:abcd-
      
    • 截取位置0后3个字符

      word=abcd-//master-01://httpab
      echo ${word:0:3} 
      # 输出:abc
      
    • 从位置1截取到末尾

      word=abcd-//master-01://httpab
      echo ${word:1} 
      # 输出:bcd-//master-01://httpab
      
    • 从位置-1截取到末尾,就是截取最后一个

      word=abcd-//master-01://httpab
      echo ${word:(-1)} 
      # 输出:b
      
  2. 字符串替换

    • 从左到右,匹配第一个,替换//为cd
      word=abcd-//master-01://httpab
      echo ${word/\/\//cd} 
      # 输出:abcd-cdmaster-01://httpab
      
    • 将所有匹配的//替换为cd
      word=abcd-//master-01://httpab
      echo ${word//\/\//cd} 
      # 输出:abcd-cdmaster-01:cdhttpab
      
    • 前缀匹配,只匹配从位置0开始的字符
      word=abcd-//master-01://httpab
      echo ${word/#ab/cd} 
      # -不是前缀,会匹配失败
      echo ${word/#-/cd}
      # 输出:abcd-cdmaster-01://httpab
      # 输出:abcd-//master-01://httpab
      
    • 后缀匹配,只匹配结尾字符
      word=abcd-//master-01://httpab
      echo ${word/%http*/xy} 
      # 输出:abcd-//master-01://xy
      echo ${word/%ab/xy}
      # 输出:abcd-//master-01://httpxy
      echo ${word/%ab*/xy}
      # 出现*,会从起始匹配
      # 输出:xy
      
  3. 字符串删除

    • 利用字符截取和替换,以及拼接可以实现删除字符的效果

    • 删除前3个字符

      word=abcd-//master-01://httpab
      echo ${word#*${word:0:3}} 
      # 输出:d-//master-01://httpab
      
    • 删除后3个字符

      word=abcd-//master-01://httpab
      echo ${word%*${word:(-3)}} 
      # 输出:abcd-//master-01://htt
      
    • 删除第一个ab

      word=abcd-//master-01://httpab
      echo ${word/ab/} 
      # 输出:cd-//master-01://httpab
      
    • 删除所有ab

      word=abcd-//master-01://httpab
      echo ${word//ab/} 
      # 输出:cd-//master-01://http
      
    • 删除最后一个ab

      word=abcd-//master-01://httpabcd
      echo ${word%ab*}${word##*ab}
      # 输出:abcd-//master-01://httpcd
      
  4. 字符串trim

    • 利用xargs可以实现trim
      word="   hello  wolrd  "
      word=`echo $word | xargs`
      echo $word
      # 输出:hello  wolrd
      

参考博客:https://www.cnblogs.com/gaochsh/p/6901809.html

你可能感兴趣的:(linux,shell,字符串,Linux,shell,截取)