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替換
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章