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

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

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

6.字符(串)的替换
方法:
$echo ${variable/oldletter/newletter}                                          #替换一个
$echo ${variable//oldletter/newletter}                                         #替换所有
code:
[code:1]zhyfly: ~$ x="this is a test"
zhyfly: ~$ echo ${x/i/m}
thms is a test
zhyfly: ~$ echo ${x//i/m}
thms ms a test[/code:1]
辛苦 辛苦
[quote:7a990e222f="BOoRFGOnZ"]辛苦 辛苦[/quote]
呵呵,应该的

总结一下,由此可见bash下字符串的处理主要是echo和expr,另外应理解${}的应用!
补充:
1.$()用于命令的替换等价于反引号``(注意不要和' '混淆)区别是反引号可以嵌套
code:
[code:1]zhyfly: ~$ pwd
/home/zhyfly
zhyfly: ~$ echo $(pwd)
/home/zhyfly
zhyfly: ~$ echo `pwd`
/home/zhyfly
[/code:1]
2.()和{}都可以用于命令群组(command group),区别为
()---在子shell中执行,称为nested sub shell
{}---在同一个shell中执行,称为non-named command group,它还被用于函数的定义(function)及变量的替换.
code:
[code:1]zhyfly: ~$ a=this
zhyfly: ~$ b=that
zhyfly: ~$ echo $a and $b
this and that
zhyfly: ~$ echo $aand$b
that
zhyfly: ~$ echo ${a}and$b
thisandthat
[/code:1]
进程替换呢?
你可以添加啊,我就了解这些了