Linux shell字符操作总结
各符号介绍
字符串长度统计
- ${#string}: 字符串string的长度
字符串截取
- ${string#*substring}: 从左到右截取特定字符substring第一次出现位置之后的字符串
- ${string##*substring}: 从左到右截取特定字符substring最后一次出现位置之后的字符串
- ${string%substring*} : 从右到左截取特定字符substring第一次出现位置之后的字符串
- ${string%%substring*}: 从右到左截取特定字符substring最后一次出现位置之后的字符串
- ${string:num1:num2}: 截取从位置num1开始长度为num2的字符
- ${string:num1}: 截取从位置num1开始的字符,不指定长度,默认到字符串最后
- ${string:(-num1)}: 截取字符串尾部向前长度为num1的字符
匹配并替换
- ${string/substring/string2}: 从左到右,使用string2代替第一个匹配的substring
- ${string//substring/string2}: 从左到右,使用string2代替所有匹配的substring
- ${string/#substring/string2}: 将匹配substring的string前缀替换为string2
- ${string/%substring/string2}: 将匹配substring的string后缀替换为string2
字符串删除
- ${string/substring}: 从左到右,删除第一个匹配的substring
字母大小写转换
- ${string^^}: 将字符串string转换成大写
- ${string^^a}: 将字符串string中的字母a转换成大写
- ${string,,}: 将字符串string转换成小写
- ${string,,A}: 将字符串string中的字母A转换成小写
代码示例
~/tmp$ html="https://www.cnblogs.com/chaimy/p/17041668.html//https://www.cnblogs.com/chaimy/p/17041668.html"
#字符串长度统计
~/tmp$ echo ${#html}
94
#字符串截取
~/tmp$ echo ${html#*chai}
my/p/17041668.html//https://www.cnblogs.com/chaimy/p/17041668.html
~/tmp$ echo ${html##*chai}
my/p/17041668.html
~/tmp$ echo ${html%chai*}
https://www.cnblogs.com/chaimy/p/17041668.html//https://www.cnblogs.com/chaimy/p/17041668.html
~/tmp$ echo ${html%%chai*}
https://www.cnblogs.com/
~/tmp$ echo ${html:0:6}
https:
~/tmp$ echo ${html:1}
ttps://www.cnblogs.com/chaimy/p/17041668.html//https://www.cnblogs.com/chaimy/p/17041668.html
~/tmp$ echo ${html:(-4)}
html
#匹配并替换
~/tmp$ string="abc123abc123abc123"
~/tmp$ echo ${string/123/666}
abc666abc123abc123
~/tmp$ echo ${string//123/666}
abc666abc666abc666
~/tmp$ echo ${string/#123/666}
abc123abc123abc123
~/tmp$ echo ${string/#abc/666}
666123abc123abc123
~/tmp$ echo ${string/%123/666}
abc123abc123abc666
#字符串删除
~/tmp$ string="abc123abc123abc123"
~/tmp$ echo ${string/123}
abcabc123abc123
#字母大小写转换
~/tmp$ string="aBaC"
~/tmp$ echo ${string^^}
ABAC
~/tmp$ echo ${string^^a}
ABAC
~/tmp$ echo ${string,,}
abac
~/tmp$ echo ${string,,B}
abaC