5-1-2-shell:字符串处理基础--echo篇

长度

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位

截取长度:2

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"

删除

按照上述替换规则,替换为""即可 
posted @ 2021-07-11 11:14  繁忙的蜜蜂  阅读(232)  评论(0编辑  收藏  举报