前言
在shell脚本中或者terminal指令中,经常会涉及到字符串相关操作。有很多命令语句,如:awk,sed都可以做字符串各种操作。 其实shell内置一系列操作符号,可以达到类似效果,大家知道,使用内部操作符会省略启动外部程序等时间,因此速度会非常的快。
获取长度、读取、替换的一系列指令
${#string} $string的长度
${string:position} 在$string中, 从位置$position开始提取子串
${string:position:length} 在$string中, 从位置$position开始提取长度为$length的子串
${string#substring} 从变量$string的开头, 删除最短匹配$substring的子串
${string##substring} 从变量$string的开头, 删除最长匹配$substring的子串
${string%substring} 从变量$string的结尾, 删除最短匹配$substring的子串
${string%%substring} 从变量$string的结尾, 删除最长匹配$substring的子串
${string/substring/replacement} 使用$replacement, 来代替第一个匹配的$substring
${string//substring/replacement} 使用$replacement, 代替所有匹配的$substring
${string/#substring/replacement} 如果$string的前缀匹配$substring, 那么就用$replacement来代替匹配到的$substring
${string/%substring/replacement} 如果$string的后缀匹配$substring, 那么就用$replacement来代替匹配到的$substring
替换字符
str="apple, tree, apple tree"
echo ${str/apple/APPLE} # 替换第一次出现的apple
# 输出APPLE, tree, apple tree
echo ${str//apple/APPLE} # 替换所有apple
# 输出 APPLE, tree, APPLE tree
echo ${str/#apple/APPLE} # 如果字符串str以apple开头,则用APPLE替换它
echo ${str/%apple/APPLE} # 如果字符串str以apple结尾,则用APPLE替换它
也可以用作分割字符串处理,例如:
str="apple, tree, apple tree"
echo ${str//,/##} # 英文逗号, 替换成##
# 输出 apple##tree##APPLE tree
分割、截取字符串
1. 使用 # 和 ## :截取的是指定字符后边内容
val=“hello_world_shell”
echo ${val#*_}
# 只删掉第一个 _ 前边的字符,截取剩下后边的内容
# 输出: world_shell
echo ${val##*_}
# 删除最后一个 _ 前边的字符,只截取最后一个 _ 后边内容
# 输出: shell
这里的 * 表示的是通配符
示例: 截取文件的后缀,去掉文件名字
str_file="123.hello.json"
echo ${str_file##*.}
# 删掉最后一个 . 前边的123.hello
# 输出: json
2. 使用%和%%:截取的是指定字符前边内容
val=“hello++world++shell”
echo ${val%++*}
# 删除最后一个 ++ 后边字符,截取前边剩下的内容
# 输出: hello++world
echo ${val%%++*}
# 删除第一个 ++ 后边字符,只截取保留第一个 ++ 前边的内容
# 输出: hello
示例 截取文件名字,去掉后缀
str_file="123.hello.json"
echo ${str_file%.*}
# 删除最后一个 . 后边的json,截取123.hello
# 输出: 123.hello
3. 使用{:}或者${::}: 根据字符索引来截取
val=“hello world!”
ehco ${val:4:5}
# 输出: o wor
这个简单易懂,这里的4代表的是字符‘o’,即从左边开始算的第5个字符开始。
5代表是截取的字符个数。所以就是从第四个字符开始,截取5个字符。
val=“hello world!”
echo ${val:5}
# 输出:world!
代表的就是从左边第5个字符到最后一个字符
val=“hello world!”
echo ${val:0-10:3}
#输出:llo
从右边第10个字符开始截取3个字符。