首页 > 系统服务 > 详细

shell 字符串处理-echo

时间:2021-04-18 21:40:07      阅读:25      评论:0      收藏:0      [点我收藏+]

长度

str=this is a test str.
echo ${#str} 

结果: "19"

拼接

a="123"
b="abc"
c="{|}"

d1=${a}${b}${c}
echo ${d1}
结果:"123abc{|}"

d2=${a}"\n"${b}"\n"${c}
echo ${d2}
结果:"123abc{|}"
echo -e ${d2} 结果: "123" "abc" "{|}" # 输出时打开转义 echo -e # 输出时关闭转义 echo -E

截取--索引

从左边开始计数1位的位置开始截取长度5

str=this is a test str.
echo ${str:1:5}

结果: "his i"

从左边开始计数2位的位置开始截取到末尾

str=this is a test str.
echo ${str:2}

结果: "is is a test str."

从左边开始计数3位的位置开始截取长度5

str=this is a test str.
echo ${str:0-3:2}

结果: "tr"

从左边开始计数4位的位置开始截取到末尾

str=this is a test str.
echo ${str:0-3}

结果: "str."

截取--子字符串

匹配开始位置

str="this is a test str."

# 首字母开始匹配
echo ${str#thi}
结果 "s is a test str."

# 任意字符开始匹配
echo ${str#*hi}
结果: "s is a test str."

匹配之后输出位置

str="this is a test str."

echo ${str#*is}
结果: "is a test str."

echo ${str##*is}
结果: "a test str."

多次匹配

a="is 1 is 2 is 3 is 4 is 5 is 6 is 7 is 8"

echo ${a#*is*is} 结果:"2 is 3 is 4 is 5 is 6 is 7 is 8" echo ${a##*is*is} 结果:"8"

替换

a="is 1 is 2 is 3 is 4 is 5 is 6 is 7 is 8 is"

#从头开始查找,替换第一个
echo ${a/is/at}
结果:"at 1 is 2 is 3 is 4 is 5 is 6 is 7 is 8 is"

#从第一个字符开始匹配替换
echo ${a/#is/at}
结果:"at 1 is 2 is 3 is 4 is 5 is 6 is 7 is 8 is"

#从最后一个字符开始匹配替换
echo ${a/%is/at}
结果:"is 1 is 2 is 3 is 4 is 5 is 6 is 7 is 8 at"

# 全部替换
echo ${a//is/at}
结果:"at 1 at 2 at 3 at 4 at 5 at 6 at 7 at 8 at"

删除

按照上述替换规则,替换为""即可 

shell 字符串处理-echo

原文:https://www.cnblogs.com/lamp-lrh/p/14673750.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!