1、使用unix自带的方法:

${varible##*string} 从左向右截取最后一个string后的字符串

${varible#*string}从左向右截取第一个string后的字符串

${varible%%string*}从右向左截取最后一个string后的字符串

${varible%string*}从右向左截取第一个string后的字符串

"*"只是一个通配符可以不要


$ test1=123456.txt
$ echo ${test1%.txt}
123456
$ echo ${test1#*23}
456.txt

$ test2=${test1%.txt}'.rst'

$ echo $test2

123456.rst


2、使用cut命令

$ test1=123456.txt
$ echo $test1|cut -f 1 -d .

123456


此处我略有疑问,为什么不能将此值赋值给另一个变量?比如:

$ test2=echo $test1|cut -f 1 -d .

ksh: 123456.txt:  not found.

$ echo test2=$test1|cut -f 1 -d .

test2=123456

$ echo $test2


此处test2无值,why?


忽然想到shell中的反引号了,TAB键上面的那个,反引号引起来的部分会优先执行,做了下测试:

$ test2=`echo $test1|cut -f 1 -d .`

$ echo $test2

123456

$ test2=`echo $test1|cut -f 1 -d .`'.rst'

$ echo $test2

123456.rst


成功!