bash中字符串的处理
1.得到字符串长度
方法一:
$echo ${#variable}
code:
zhyfly: ~$
x="this is a test"
zhyfly: ~$ echo ${#x}
14
$expr length "$variable"
code:
zhyfly: ~$x="this
is a test"
zhyfly: ~$
expr length "$x"
14
$expr "$variable" : ".*"
code:
zhyfly: ~$x="this
is a test"
zhyfly: ~$
expr "$x" :".*"
14
方法:
$expr index "$variable" "substring"
code:
zhyfly: ~$x="this
is a test"
zhyfly: ~$
expr index "$x" "is"
3
zhyfly: ~$ expr index"$x" "t"
1
3.得到字符串子字符串
方法一:
$echo ${variable:position:length}
code:
zhyfly: ~$x="this
is a test"
zhyfly: ~$ echo ${x:1:5}
his i
$expr substr "$variable" startposition length
code:
zhyfly: ~$x="this
is a test"
zhyfly: ~$
expr substr "$x"
1 5
this
4.匹配正则表达式之匹配长度
方法:
$expr match "$x" "string"
code:
zhyfly: ~$x="this
is a test"
zhyfly: ~$
expr match "$x" "his"
0
zhyfly: ~$ expr match"$x" "this"
4
zhyfly: ~$ expr match"$x" "."
1
方法:
$echo ${variable#startletter*endletter} # #表示掐头,因为键盘上#在$前面,一个表示最小匹配
$echo ${variable##tartletter*endletter} 两个表示最大匹配
$echo ${variable%startletter*endletter} # %表示去尾,因为键盘上%在$后面,一个表示最小匹配
$echo ${variable%%startletter*endletter} 两个表示最大匹配
code:
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
6.字符(串)的替换
方法:
$echo ${variable/oldletter/newletter} #替换一个
$echo ${variable//oldletter/newletter} #替换所有
code:
zhyfly: ~$x="this
is a test"
zhyfly: ~$ echo ${x/i/m}
thms is a test
zhyfly: ~$ echo ${x//i/m}
thms ms a test
1245

被折叠的 条评论
为什么被折叠?



