LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 6082|回复: 3

bash中字符串的处理(参阅CU一贴后重整理)

[复制链接]
发表于 2005-3-8 07:59:08 | 显示全部楼层 |阅读模式
1.得到字符串长度
方法一:
$echo ${#variable}
code:
[PHP]
zhyfly: ~$ x="this is a test"
zhyfly: ~$ echo ${#x}
14[/PHP]
方法二:
$expr length "$variable"
code:
[PHP]
zhyfly: ~$ x="this is a test"
zhyfly: ~$ expr length "$x"
14[/PHP]
方法三:
$expr "$variable" : ".*"
code:
[PHP]
zhyfly: ~$ x="this is a test"
zhyfly: ~$ expr "$x" : ".*"
14[/PHP]
2.查找字符串子串位置
方法:
$expr index "$variable" "substring"
code:
[PHP]
zhyfly: ~$ x="this is a test"
zhyfly: ~$ expr index "$x" "is"
3
zhyfly: ~$ expr index "$x" "t"
1[/PHP]
(ps:如果出现重复,好象只能查到第一个,第二个,第三个,...,怎么查到呢???)
3.得到字符串子字符串
方法一:
$echo  ${variable:position:length}
code:
[PHP]
zhyfly: ~$ x="this is a test"
zhyfly: ~$ echo ${x:1:5}
his i[/PHP]
方法二:
$expr substr "$variable" startposition length
code:
[PHP]
zhyfly: ~$ x="this is a test"
zhyfly: ~$ expr substr "$x" 1 5
this[/PHP]
(ps:注意方法一和方法二中位置的区别!)
4.匹配正则表达式之匹配长度
方法:
$expr match "$x" "string"
code:
[PHP]
zhyfly: ~$ x="this is a test"
zhyfly: ~$ expr match "$x" "his"
0
zhyfly: ~$ expr match "$x" "this"
4
zhyfly: ~$ expr match "$x" "."
1[/PHP]
5.字符串的掐头去尾
方法:
$echo ${variable#startletter*endletter}                               # #表示掐头,因为键盘上#在$前面,一个表示最小匹配
$echo ${variable##tartletter*endletter}                                                                              两个表示最大匹配
$echo ${variable%startletter*endletter}                               # %表示去尾,因为键盘上%在$后面,一个表示最小匹配
$echo ${variable%%startletter*endletter}                                                                               两个表示最大匹配
code:
[PHP]
zhyfly: ~$ x="this is a test"
zhyfly: ~$ echo ${x#t}
his is a test
zhyfly: ~$ echo ${x#t*h}
is is a test
zhyfly: ~$ echo ${x#t*s}
is a test

zhyfly: ~$ echo ${x##t*s}
t

zhyfly: ~$ echo ${x%t}
this is a tes
zhyfly: ~$ echo ${x%s*t}
this is a te
zhyfly: ~$ echo ${x%e*t}
this is a t

zhyfly: ~$ echo ${x%%i*t}
th[/PHP]

6.字符(串)的替换
方法:
$echo ${variable/oldletter/newletter}                                          #替换一个
$echo ${variable//oldletter/newletter}                                         #替换所有
code:
[PHP]
zhyfly: ~$ x="this is a test"
zhyfly: ~$ echo ${x/i/m}
thms is a test
zhyfly: ~$ echo ${x//i/m}
thms ms a test[/PHP]
发表于 2005-3-8 09:05:45 | 显示全部楼层
加精
同时也可参阅下面的帖子,互为补充
http://www.linuxsir.cn/bbs/showthread.php?t=180140
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-3-8 10:38:21 | 显示全部楼层
多谢版主!!!
回复 支持 反对

使用道具 举报

发表于 2006-11-6 16:19:26 | 显示全部楼层
好东西
6个字
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表