Shell 字符串截取

代码走起

1
2
3
4
5
6
7
8
9
10
11
12
13
str="http://www.baidu.com/demo"
# 从左计数到 start( 0 开始)截取 n 长度 ; ${string:start:length} ; length 不填则直接到最后
echo ${str:0:4}
# 从右计数到 start( 1 开始) 截取 n 长度 ; ${string:0-start:length} ; length 不填则直接到最后
echo ${str:0-4:4}
# 从指定字符串(第一个)开始截取,取右边全部 ${string#*chars}
echo ${str#*/}
# 从指定字符串(最后一个)开始截取,取右边全部 ${string##*chars}
echo ${str##*/}
# 从指定字符串(第一个)开始截取,取左边全部 ${string%chars*}
echo ${str%/*}
# 从指定字符串(最后一个)开始截取,取左边全部 ${string%%chars*}
echo ${str%%/*}