`
LIMIMGJIE
  • 浏览: 171942 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

bash shell的字符串处理

阅读更多
${#str} str的长度

expr length "$str"

expr "$str" : '.*'

匹配字符串开头的字串长度,

expr match "$str" '$sub'

expr "$str" : '$sub'

               str=abcABC123ABCabc
                       ^------------------^
               echo `expr "$str" : '.*ABC'`   #12

索引

expr index $str $sub

取子串

${str:position}
${str:position:length}
expr substr $str $position $length
expr match "$str" '\($sub\)'   #从开始取到substr
expr "$str" : '\($sub\)'
expr match "$str" '.*\($sub\)' #从结尾取到substr
expr "$str" : '.*\($sub\)'

子串删除

${str#sub}    # 从开始去掉在最小匹配的$sub
${str##sub} # 最大
${str%sub}   #从结尾
${str%%sub} #最大匹配

子串替换

${str/sub/repl}     #用repl替换第一个匹配的sub
${str//sub/repl}    #替换所有匹配
${str/#sub/repl}    #如果sub匹配str的开头部分,则用repl替换
${str/%sub/repl} #如果sub匹配str的结尾部分,则用repl替换
分享到:
评论
Global site tag (gtag.js) - Google Analytics