Linux shell string 操作

12 篇文章 0 订阅

Linux shell 字符串操作总结

1.判断读取字符串值

varvar, var相同

varDEFAULTvar, DEFAULT作为其值 *
var:DEFAULTvar,, DEFAULT作为其值 *

var=DEFAULTvar, DEFAULT作为其值 *
var:=DEFAULTvar,, DEFAULT作为其值 *

var+OTHERvar, OTHER, 否则就为null字符串
var:+OTHERvar, OTHER, 否则就为null字符串

var?ERRMSGvar, ERR_MSG *
var:?ERRMSGvar, ERR_MSG *

!varprefixvarprefix {!varprefix@} 匹配之前所有以varprefix开头进行声明的变量

字符串操作

{#string}string的长度

string:position string中, 从位置 position {string:position:length} 在 string, position开始提取长度为$length的子串

{string#substring} 从变量string的开头, 删除最短匹配 substring {string##substring} 从变量 string, substring的子串
{string%substring} 从变量string的结尾, 删除最短匹配 substring {string%%substring} 从变量 string, substring的子串

string/substring/replacement使 replacement, 来代替第一个匹配的 substring {string//substring/replacement} 使用 replacement, substring
{string/#substring/replacement} 如果string的前缀匹配 substring, replacement来代替匹配到的 substring {string/%substring/replacement} 如果 string substring, 那么就用 replacement substring

1.长度

[web97@salewell97 ~] test=Ilovechina[web97@salewell97 ] echo ${#test}
12

${#变量名}得到字符串长度

2.截取字串

[chengmo@localhost ~] test=Ilovechina[chengmo@localhost ] echo test:5echina[chengmo@localhost ] echo ${test:5:10}
e china

${变量名:起始:长度}得到子字符串

3.字符串删除

[chengmo@localhost ~] test=c:/windows/boot.ini[chengmo@localhost ] echo {test#/}  
c:/windows/boot.ini  
[chengmo@localhost ~]
echo {test#*/}  
windows/boot.ini  
[chengmo@localhost ~]
echo ${test##*/}
boot.ini

[chengmo@localhost ~] echo {test%/*}
c:/windows
[chengmo@localhost ~] echo {test%%/*}

${变量名#substring正则表达式}从字符串开头开始配备substring,删除匹配上的表达式。

${变量名%substring正则表达式}从字符串结尾开始配备substring,删除匹配上的表达式。

注意:{test##*/},{test%/*} 分别是得到文件名,或者目录地址最简单方法。

4.字符串替换

[chengmo@localhost ~] test=c:/windows/boot.ini[chengmo@localhost ] echo {test/\//\}  
c:\windows/boot.ini  
[chengmo@localhost ~]
echo ${test//\//\}
c:\windows\boot.ini

${变量/查找/替换值} 一个“/”表示替换第一个,”//”表示替换所有,当查找中出现了:”/”请加转义符”\/”表示。

三、性能比较

在shell中,通过awk,sed,expr 等都可以实现,字符串上述操作。下面我们进行性能比较。

[chengmo@localhost ~] test=c:/windows/boot.ini[chengmo@localhost ] time for i in (seq10000);doa= {#test};done;

real 0m0.173s
user 0m0.139s
sys 0m0.004s

[chengmo@localhost ~] timeforiin (seq 10000);do a= (exprlength test);done;

real 0m9.734s
user 0m1.628s

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值