标签:
shell中截取字符串的方法很多
${var#*/} ${var##*/} ${var%/*} ${var%%/*} ${var:start:len} ${var:start} ${var:0-start:len} ${var:0-start}
下面用几个例子展示一下:
语法:
${#var}
示例代码:
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]
语法:
${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 : [/www.fengbohello.xin3e.com/blog/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 : [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]
本文同步发表于这里:http://www.fengbohello.xin3e.com/point/p/629
作者: 风波
mail: fengbohello@foxmail.com
标签:
原文地址:http://www.cnblogs.com/fengbohello/p/5954895.html