${var#Pattern}
Remove from $var
the shortest part of $Pattern
that matches the front end of $var
.
${var##Pattern}
Remove from $var
the longest part of $Pattern
that matches the front end of $var
.
${var%Pattern}
Remove from $var
the shortest part of $Pattern
that matches the back end of $var.
${var%%Pattern}
Remove from $var
the longest part of $Pattern
that matches the back end of $var
.
简言之:
#
是将${var}
中的左边(键盘上 #
在 $
的左边)的${Pattern}
去掉;
%
是将${var}
中的右边(键盘上 %
在 $
的右边)的${Pattern}
去掉;
其中单一符号#
或%
是最小匹配;两个符号##
或%%
则是最大匹配。
${string/substring/replacement}
Replace first match of $substring
with $replacement
.
${string//substring/replacement}
Replace all matches of $substring
with $replacement
.
#!/bin/sh
str="This is This is my test string search_string" #被测试字符串
subStr1="This is " #待删除的字符串1
subStr2="string" #待删除的字符串2
echo -e "Test 1 ${str#$subStr1}"
echo -e "Test 2 ${str##$subStr1}"
echo -e "Test 3 ${str#$subStr2}"
echo -e "Test 4 ${str##$subStr2}"
echo -e "Test 5 ${str#*$subStr1}"
echo -e "Test 6 ${str##*$subStr1}"
echo -e "Test 7 ${str##*$subStr1*}"
echo -e "Test 8 ${str##*$subStr2}"
echo -e "Test 9 ${str##*$subStr2*}"
echo -e
echo -e "Test 10 ${str%$subStr1}"
echo -e "Test 11 ${str%%$subStr1}"
echo -e "Test 12 ${str%$subStr2}"
echo -e "Test 13 ${str%%$subStr2}"
echo -e "Test 14 ${str%*$subStr1}"
echo -e "Test 15 ${str%%$subStr1*}"
echo -e "Test 16 ${str%*$subStr1*}"
echo -e "Test 17 ${str%$subStr2*}"
echo -e "Test 18 ${str%*$subStr2}"
echo -e "Test 19 ${str%%*$subStr2}"
echo -e "Test 20 ${str%%$subStr2*}"
echo -e "Test 21 ${str%%*$subStr2*}"
其输出为:
Test 1 This is my test string search_string
Test 2 This is my test string search_string
Test 3 This is This is my test string search_string
Test 4 This is This is my test string search_string
Test 5 This is my test string search_string
Test 6 my test string search_string
Test 7
Test 8
Test 9
Test 10 This is This is my test string search_string
Test 11 This is This is my test string search_string
Test 12 This is This is my test string search_
Test 13 This is This is my test string search_
Test 14 This is This is my test string search_string
Test 15
Test 16 This is
Test 17 This is This is my test string search_
Test 18 This is This is my test string search_
Test 19
Test 20 This is This is my test
Test 21
#!/bin/sh
str="This is This is my test string search_string" #被测试字符串
subStr="This is " #待替换的字符串
replaceStr="TTT " #替换的字符串
echo -e "Test 1 ${str/$subStr/$replaceStr}"
echo -e "Test 2 ${str//$subStr/$replaceStr}"
其输出为:
Test 1 TTT This is my test string search_string
Test 2 TTT TTT my test string search_string
HTML 版本:Advanced Bash-Scripting Guide -10.2. Parameter Substitution
PDF 版本:Advanced Bash-Scripting Guide P133页