Shell 字符串处理

在 Wed 18 June 2014 发布于 Shell 分类

字符串的长度

stringZ=abcABc123ABCabc
echo ${#stringZ}
echo `expr length $stringZ`
echo `expr "$stringZ" : '.*'`

从字符串的起始位置开始进行匹配, 返回匹配子串的长度

stringZ=abcABC123ABCabc

echo `expr match "$stringZ" 'abc[A-Z]*.2'`  #8
echo `expr "$stringZ" : 'abc[A-Z]*.2'` #8

从目标串中找出第一次出现模式串中的字符位置, 并返回其下标(下标从1开始)

stringZ=abcABC123ABCabc
echo `expr index "$stringZ" C12` #6

echo `expr index "$stringZ" 1c` #3

${string:position} 从position开始提取剩下的子串

${string:position:length}position开始提取长度为length长度的子串

stringZ=abcABC123ABCabc
echo ${stringZ:0}  #abcABC123ABCabc
echo ${stringZ:1}  #bcABC123ABCabc
echo ${stringZ:7}  #23ABCabc
echo ${stringZ:7:3} #23A
#当position为负数的时候, 表示从字符串结尾往字符串开始索引,需要注意的是position必须用括号括起来.
echo ${stringZ:-4} #abcABC123ABCabc
echo ${stringZ:(-4)} #Cabc

${string#substring}目标字符串左侧开始进行匹配, 并消除最短匹配串

${string##substring}目标字符串左侧开始进行匹配, 并消除最长匹配串

stringZ=abcABC123ABCabc
echo ${string#a*C} #123ABCabc
echo ${stringZ##a*c} #abc

#
X=a*C
echo ${stringZ#$X}   #123ABCabc
echo ${stringZ#$X}   #abc

${string%substring}目标字符串右侧开始进行匹配, 并消除最短匹配串

${string%%substring}目标字符串右侧开始进行匹配, 并消除最短匹配串

SUFF=TXT
suff=txt

for i in $(ls *.$SUFF)
do
    mv -f $i ${i%.$SUFF}.$suff
done



stringZ=abcABC123ABCabc
echo ${stringZ%b*c}
echo ${stringZ%%b*c}

${string/substring/replacement}替换目标串中第一个匹配模式串substring的子串为replacement

${string//substring/replacement}替换目标串中所有匹配模式串substring的子串为replacement

stringZ=abcABC123ABCabc
echo ${stringZ/abc/xyz}  #xyzABC123ABCabc
echo ${stringZ//abc/xyz} #xyzABC123ABCxyz
echo ----------
echo "$stringZ"  #abcABC123ABCabc
echo ---------

#若replace为空则为消除操作
echo ${stringZ/abc}  #ABC123ABCabc
echo ${stringZ//abc} #ABC123ABC

${string/#substring/replacement}, 从目标字符串的左侧还是匹配, 把第一个匹配模式串substring的子串替换成replacement

${string/%substring/replacement}, 从目标字符串的左侧还是匹配, 把第一个匹配模式串substring的子串替换成replacement

stringZ=abcABC123ABCabc
echo ${stringZ/#abc/XYZ}  # XYZABC123ABCabc

echo ${stringZ/%abc/XYZ}  # abcABC123ABCXYZ