shell中截取字符串的方法不少shell
${var#*/} ${var##*/} ${var%/*} ${var%%/*} ${var:start:len} ${var:start} ${var:0-start:len} ${var:0-start}
下面用幾個例子展現一下:spa
語法:code
${#var}
示例代碼:blog
str="http://www.fengbohello.xin3e.com/blog/shell-truncating-string" echo "string : [${str}]" length=${#str} echo "length : [${length}]"
執行結果:字符串
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] length : [61]
語法:get
${parameter#word}
示例代碼:同步
str="http://www.fengbohello.xin3e.com/blog/shell-truncating-string" echo "string : [${str}]" #分割符爲'/' substr=${str#*/} echo "substr : [${substr}]"
執行結果:string
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] substr : [/www.fengbohello.xin3e.com/blog/shell-truncating-string]
語法:class
${parameter##word}
示例代碼:語法
str="http://www.fengbohello.xin3e.com/blog/shell-truncating-string" echo "string : [${str}]" #分割符爲'/' substr=${str##*/} echo "substr : [${substr}]"
執行結果:
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] substr : [shell-truncating-string]
語法:
${parameter%word}
示例代碼:
str="http://www.fengbohello.xin3e.com/blog/shell-truncating-string" echo "string : [${str}]" substr=${str%/*} echo "substr : [${substr}]"
執行結果:
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] substr : [http://www.fengbohello.xin3e.com/blog]
語法:
${parameter%%word}
示例代碼:
str="http://www.fengbohello.xin3e.com/blog/shell-truncating-string" echo "string : [${str}]" substr=${str%%/*} echo "substr : [${substr}]"
執行結果:
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] substr : [http:]
語法:
${var:start:len}
示例代碼:
str="http://www.fengbohello.xin3e.com/blog/shell-truncating-string" echo "string : [${str}]" #其中的 0 表示左邊第一個字符開始,7 表示子字符的總個數。 substr=${str:0:7} echo "substr : [${substr}]"
執行結果:
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] substr : [http://]
語法:
${var:7}
示例代碼:
str="http://www.fengbohello.xin3e.com/blog/shell-truncating-string" echo "string : [${str}]" #其中的 7 表示左邊第8個字符開始 substr=${str:7} echo "substr : [${substr}]"
執行結果:
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] substr : [www.fengbohello.xin3e.com/blog/shell-truncating-string]
語法:
${var:0-start:len}
示例代碼:
str="http://www.fengbohello.xin3e.com/blog/shell-truncating-string" echo "string : [${str}]" #其中的 0-23 表示右邊算起第23個字符開始,5 表示字符的個數 substr=${str:0-23:5} echo "substr : [${substr}]"
執行結果:
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] substr : [shell]
語法:
${var:0-start}
示例代碼:
str="http://www.fengbohello.xin3e.com/blog/shell-truncating-string" echo "string : [${str}]" #其中的 0-6 表示右邊算起第6個字符開始 substr=${str:0-6} echo "substr : [${substr}]"
執行結果:
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] substr : [string]