首页 > 其他 > 详细

Unix字符串截取

时间:2014-02-19 11:41:02      阅读:412      评论:0      收藏:0      [点我收藏+]

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


成功!







本文出自 “路漫漫其修远兮…” 博客,请务必保留此出处http://baser.blog.51cto.com/4153192/1360103

Unix字符串截取

原文:http://baser.blog.51cto.com/4153192/1360103

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!