美文网首页
shell字符串操作

shell字符串操作

作者: 安全老司机 | 来源:发表于2020-05-18 20:41 被阅读0次

1.1 按照下标截取

str="hello world"
#从下标1开始,截取3个字符
echo ${str:1:3}
ell

#从下标0开始,截取到倒数第6个
echo ${str::-6}
hello

#从下标0开始,截取5个字符
echo ${str::5}
hello

#从下标1开始,截取到末尾
echo ${str:1}
ello world

1.2 字符串长度

str="hello world"
echo ${#str}
11

1.3 字符串删除

str="hello world"
#从前面删,匹配到第一个l字符,相当于startWith的最短匹配
echo ${str#h*l}
lo world

#从前面删除,相当于startWith的最长匹配
echo ${str##h*l}
d

#从后面删除,相当于endWith最短匹配
echo ${str%l*}
hello wor

#从后面删除,相当于endWith最长匹配
echo ${str%%l*}
he

1.4 字符串替换

#替换第一个l
echo ${str/l/L}
heLlo world

#替换所有l
echo ${str//l/L}
heLLo worLd

相关文章

网友评论

      本文标题:shell字符串操作

      本文链接:https://www.haomeiwen.com/subject/gzupohtx.html