查找子字符串长度 expr match “string” ‘substring’。这里的substring是正则表达式。例如expr match “abcdefg123456” ‘[a-z]*[0-9]',这个就返回8。这里的正则表达式[a-z]*[0-9]刚好匹配到了abcdefg1,所以长度为8。
抽取子字符串 expr substr string pos len。这个相当于C++的std::string中的substr()。不同的是这里的pos的下标从1开始,而std::string的下标从0开始。例如 expr substr “abcdefg123456” 1 6,将抽取子串为abcdef,从第一个开始,长度为6。
其实bash中的字符串操作函数非常丰富,而且种类也很多。比如刚才的子串长度就有另外的写法:expr "$string" : '$substring'。抽取子串也有:${string:position}和${string:position:length}两种。这些不同形式的字符串操作既带来了方便也非常容易混淆。用《Advanced Bash Scripting Guide》里的话就叫做“Bash supports a surprising number of string manipulation operations. Unfortunately, these tools lack a unified focus. Some are a subset of parameter substitution, and others fall under the functionality of the UNIX expr command. This results in inconsistent command syntax and overlap of functionality, not to mention confusion.”
以下的代码是用来将形如abc123的目前中所有*.png文件拷贝到新的地方,并为abc为目录。这里的``,就是tab上面的那个键,表示表达式求值,可以用来将``中的返回值赋值给变量。
1: for a in $(ls $srcdir)
2: do
3: len=`expr match "$a" '[a-z]*[0-9]'`
4: len=$(($len-1))
5: echo $len
6: b=`expr substr $a 1 $len`
7: echo $a to $b
8: mkdir -p $dstdir/$b
9: cp $srcdir/$a/maps/*.png $dstdir/$b/
10: done