执行结果:
string : [http://www.fengbohello.xin3e.com/blog/shell-truncating-string] substr : [shell-truncating-string]
--------------------------------------------------------------------------------
3) 使用 % 和 %% 获取头部子字符串
3.1) % 最小限度从后面截取word
语法:
${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]
3.2) %% 最大限度从后面截取word
语法:
${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:]
--------------------------------------------------------------------------------
4)使用 ${var:} 模式获取子字符串
4.1) 指定从左边第几个字符开始以及子串中字符的个数
语法:
${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://]
4.2) 从左边第几个字符开始一直到结束
语法:
${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]
4.3) 从右边第几个字符开始以及字符的个数
语法:
${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]










