bash中的字符串操作

Technorati Tags: , ,

查找子字符串长度 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

ref: http://tldp.org/LDP/abs/html/string-manipulation.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值