Pattern matching in parameter substitution
# and # # start from the left side of the string, and remove the left string,
% and percent are started from the right side of the string, and the right substring is removed.
For example
Name=hello lhhs "Root"
name=${name# ' "'}; Name=${name% ' "'}
Result is root
############################### #Start script#######################################
1 #!/bin/bash
2 # patt-matching.sh
3
4 # use # # #% of percent to match the pattern of the parameter substitution operation.
5
6 var1=abcd12345abc6789
7 Pattern1=a*c # * (wildcard characters) matches any character between a-c.
8
9 Echo
echo "var1 = $var 1" # abcd12345abc6789
echo "var1 = ${var1}" # abcd12345abc6789
# (Alternate form)
echo "Number of characters in ${var1} = ${#var1}"
Echo
15
echo "pattern1 = $pattern 1" # A*c (Everything between ' a ' and ' C ')
echo "--------------"
Echo ' ${var1# $pattern 1} = ' ${var1# $pattern 1} ' # d12345abc6789
19 # The shortest possible match, minus the first 3 characters of the abcd12345abc6789
20 # |-| ^^^
Echo ' ${var1## $pattern 1} = ' ${var1## $pattern 1} ' # 6789
22 # The furthest match, minus the first 12 characters of the abcd12345abc6789.
# |----------| ^^^^
24
echo; Echo Echo
26
Any character between pattern2=b*9 # ' B ' to ' 9 '
echo "var1 = $var 1" # or abcd12345abc6789
Echo
echo "pattern2 = $pattern 2"
echo "--------------"
Echo ' ${var1%pattern2} = ' "${var1% $pattern 2}" # abcd12345a
33 # Recent matches, minus the last 6 characters of abcd12345abc6789
# |----| ^^^^
Echo ' ${var1%%pattern2} = ' "${var1%% $pattern 2}" # A
36 # Furthest match, minus the last 12 characters of abcd12345abc6789
Panax Notoginseng # |-------------| ^^^^^^
38
39 # Remember, # and # # Start with the left side of the string, and remove the left string,
40 #% and percent of zero start from the right side of the string and remove the right substring.
41
Echo
43
0 exit
Pattern matching in bash parameter substitution