1. 长度
${#string}
myString="abc123abc456"
echo ${#myString} # 12
expr length $string
myString="abc123abc456"
expr length ${myString} # 12
2. 索引
expr index $string $substring
myString="abc123abc456"
expr index "$myString" "123" # 4
3. 子集
${string:position}
${string:position:length}
myString="abc123abc456"
echo ${myString:0} # abc123abc456
echo ${myString:4} # 23abc456
echo ${myString:3:3} # 123
4. 左右清除
${string#substring}
, 从左往右, 移除最小匹配
${string##substring}
, 从左往右, 移除最大匹配
${string%substring}
, 从右往左, 移除最小匹配
${string%%substring}
, 右右往左, 移除最大匹配
myString="abc123abc456"
echo ${myString#a*c} # 123abc456
echo ${myString##a*c} # 456
echo ${myString%c*} # abc123ab
echo ${myString%%c*} # ab
5. 替换
${string/substring/replacement}
, 只替换第一个匹配子集
${string//substring/replacement}
, 替换全部匹配子集
myString="abc123abc456"
echo ${myString/abc/XYZ} # XYZ123abc456
echo ${myString//abc/XYZ} # XYZ123XYZ456
网友评论