Linux字符串操作
描述
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} | 使用replacement来代替string前缀匹配的substring |
${string/%substring/replacement} | 使用replacement来代替string后缀匹配的substring |
示例
- ${#string}
[root@OpenWrtEXT:test]#test_str='/tmp/test/test/myvar'
[root@OpenWrtEXT:test]#echo $test_str
/tmp/test/test/myvar
[root@OpenWrtEXT:test]#echo ${#test_str}
20
[root@OpenWrtEXT:test]#
- ${string:position}
[root@OpenWrtEXT:test]#echo $test_str
/tmp/test/test/myvar
[root@OpenWrtEXT:test]#echo ${test_str:4}
/test/test/myvar
[root@OpenWrtEXT:test]#echo ${test_str:6}
est/test/myvar
[root@OpenWrtEXT:test]#
- ${string:position:length}
[root@OpenWrtEXT:test]#echo $test_str
/tmp/test/test/myvar
[root@OpenWrtEXT:test]#echo ${test_str:6:9}
est/test/
[root@OpenWrtEXT:test]#echo ${test_str:3:5}
p/tes
[root@OpenWrtEXT:test]#
- ${string#substring}
[root@OpenWrtEXT:test]#echo $test_str
/tmp/test/test/myvar
[root@OpenWrtEXT:test]#echo ${test_str#*test}
/test/myvar
[root@OpenWrtEXT:test]#
- ${string##substring}
[root@OpenWrtEXT:test]#echo $test_str
/tmp/test/test/myvar
[root@OpenWrtEXT:test]#echo ${test_str##*test}
/myvar
[root@OpenWrtEXT:test]#
- ${string%substring}
[root@OpenWrtEXT:test]#echo $test_str
/tmp/test/test/myvar
[root@OpenWrtEXT:test]#echo ${test_str%test*}
/tmp/test/
[root@OpenWrtEXT:test]#
- ${string%%substring}
[root@OpenWrtEXT:test]#echo $test_str
/tmp/test/test/myvar
[root@OpenWrtEXT:test]#echo ${test_str%%test*}
/tmp/
[root@OpenWrtEXT:test]#
- ${string/substring/replacement}
[root@OpenWrtEXT:test]#echo $test_str
/tmp/test/test/myvar
[root@OpenWrtEXT:test]#echo ${test_str/test/abc}
/tmp/abc/test/myvar
[root@OpenWrtEXT:test]#
- ${string//substring/replacement}
[root@OpenWrtEXT:test]#echo $test_str
/tmp/test/test/myvar
[root@OpenWrtEXT:test]#echo ${test_str//test/abc}
/tmp/abc/abc/myvar
[root@OpenWrtEXT:test]#
- ${string/#substring/replacement}
[root@OpenWrtEXT:test]#test_str='www.baidu.com'
[root@OpenWrtEXT:test]#echo $test_str
www.baidu.com
[root@OpenWrtEXT:test]#echo ${test_str/#www/abc}
abc.baidu.com
[root@OpenWrtEXT:test]#
- ${string/%substring/replacement}
[root@OpenWrtEXT:test]#echo $test_str
www.baidu.com
[root@OpenWrtEXT:test]#echo ${test_str/%com/abc}
www.baidu.abc
[root@OpenWrtEXT:test]#