<一> 字符串匹配,提取字符串长度
${#string}
expr length $string
expr "$string" : '.*'
匹配字符串开头的子串长度
expr match "$string" '$substring'
$substring is a regular expression
expr "$string" : '$substring'
str=abcdABCD1234dcba
echo `expr match "$str" 'abcd[A-Z]*.2'` # 10
echo `expr "$str" : 'abcd[A-Z]*.2'` # 10
|
索引expr index $string $substring
str=abcdABCD1234dcba
echo `expr index "$str" CD1` # 7; position of 'C' echo `expr index "$str" 1c` # 3; 类似于strchr()
|
提取子串${string:position} 在$string中从位置$position开始提取子串.
${string:position:length} 在$string中从位置$position开始提取$length长度的子串
str=abcABC123
echo ${str:0} # abcABC123 echo ${str:3} # ABC123 echo ${str:2:4} # cABC
echo ${str:(-4)} # C123 echo ${str: -4} # C123; 冒号后需空格
|
如果string 是"*"或"@", 将提取位置参数
echo ${*:2} #第2个和后边的所有位置参数
expr substr $string $position $length 在$string中从$position开始提取$length长度的子串.position从1开始计数,非0.
str=abcdefg
echo `expr substr $str 2 3` # bcdexpr match "$string" '\($substring\)' 从$string的开始位置提取$substring(re).
expr "$string" : '\($substring\)'
str=abcABC123ABCabc
echo `expr match "$str" '\(.[b-c]*[A-Z]..[0-9]\)'` # abcABC1 echo `expr "$str" : '\(.[b-c]*[A-Z]..[0-9]\)'` # abcABC1 echo `expr "$str" : '\(.......\)'` # abcABC1
|
expr match "$string" '.*\($substring\)' 从$string结尾提取$substring(re).
expr "$string" : '.*\($substring\)'
echo `expr "$string" : '.*\(......\)'` 从string结尾提取6个字符
<字符串子串削除>
${string#substring} 从string的开头位置截掉最短匹配的$substring.
${string##substring} 截掉最长匹配的substring.
str=abcABC123ABCabc
echo ${str#a*C} # 123ABCabc
echo ${str##a*C} # abc
${string%substring} 从string的结尾位置截掉最短匹配的$substring.
${string%%substring} 截掉最长匹配的substring.
str=abcABC123ABCabc
echo ${str%b*c} # abcABC123ABCa
echo ${str%%b*c} # a
<子串替换>
${string/substring/replacement}
使用$replacement来替换第一个匹配的$substring.
${string//substring/replacement}
使用$replacement来替换所有匹配的$substring.
str=abcABC123ABCabc echo ${str/abc/xyz} # xyzABC123ABCabc echo ${str//abc/xyz} # xyzABC123ABCxyz
|
${string/#substring/replacement}
如果$substring匹配$string的开头部分, 那么就用$replacement来替换$substring.
${string/%substring/replacement}
如果$substring匹配$string的结尾部分, 那么就用$replacement来替换$substring.
str=abcABC123ABCabc echo ${str/#abc/XYZ} # XYZABC123ABCabc echo ${str/%abc/XYZ} # abcABC123ABCXYZ
|
阅读(955) | 评论(0) | 转发(0) |