Bash字符串操作,bash字符串
分享于 点击 43428 次 点评:20
Bash字符串操作,bash字符串
1.常用操作
表达式 | 含义 |
---|---|
${#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 |
substring可以是正则表达式
2.一个例子
#!/bin/bash
mystr="hello world"
echo ${#mystr} #11
echo ${mystr:1} #ello world
echo ${mystr:1:2} #el
echo ${mystr#*l} #lo world
echo ${mystr##*l} #d
echo ${mystr%l*} #hello wor
echo ${mystr%%l*} #he
echo ${mystr/l/L} #heLlo world
echo ${mystr//l/L} #heLLo worLd
echo ${mystr/#hello/lala} #lala world
echo ${mystr/#llo/lala} #hello world
echo ${mystr/%world/lala} #hello lala
echo ${mystr/%worl/lala} #hello world
需要注意的是${string/#substring/replacement}和${string/%substring/replacement}是前缀匹配和后缀匹配,也就是说其它位置的匹配是无效的。
- 参考:
- linux shell 字符串操作(长度,查找,替换)详解
相关文章
- 暂无相关文章
用户点评