Linux shell 字符穿操作

截取

示例

1
word=abcd-//master-01://httpab

从左向右:

截取第一个//后的字符串

1
2
echo ${word#*//}
# master-01://httpab

截取最后一个//后的字符串

1
2
echo ${word##*//} 
httpab

从右向左: %

截取第一个//后的字符串

1
2
echo ${word%//*} 
abcd-//master-01:

截取第二个//后的字符串

1
2
echo ${word%%//*} 
abcd-

截取特定序列位置的字符

前3个字符

1
echo ${word:0:3}

第2到5的字符

1
2
echo ${word:1:4}
bcd-

从第二个字符到末尾

1
2
echo ${word:1}
bcd-//master-01://httpab

替换:/before/after

将第一个ab替换为AB

1
2
3
echo ${word/#ab/AB} 
或 echo ${word/ab/AB}
ABcd-//master-01://httpab

从左到右,匹配第一个,替换//为cd

1
2
echo ${word/\/\//cd}
abcd-cdmaster-01://httpab

将所有匹配的//替换为cd

1
2
echo ${word//\/\//cd}
abcd-cdmaster-01:cdhttpab

后缀匹配

1
2
3
4
5
6
7
8
word=abcd-//master-01://httpab
echo ${word/%http*/xy}
# 输出:abcd-//master-01://xy
echo ${word/%ab/xy}
# 输出:abcd-//master-01://httpxy
echo ${word/%ab*/xy}
# 出现*,会从起始匹配
# 输出:xy

删除

1
2
3
4
5
6
7
8
# 删除前3个字符
echo ${word#*${word:0:3}}
# 删除后3个字符
echo ${word%*${word:(-3)}}
# 删除第一个ab
echo ${word/ab/}
删除所有ab
echo ${word//ab/}

参考资料

https://blog.csdn.net/qq_23091073/article/details/83066518