在bash脚本中,当t="hello.txt"
两者
${t%%.txt}
和${t%.txt}
返回"hello"
同样适用于${t##*.}
和${t#*.}
返回"txt"
。
它们之间有区别吗?他们是如何运作的?
答案 0 :(得分:2)
简而言之,%%
尽可能少地移除%
。
# t="hello.world.txt"
# echo ${t%.*}
hello.world
# echo ${t%%.*}
hello
来自bash手册:
'${PARAMETER%WORD}'
'${PARAMETER%%WORD}'
The WORD is expanded to produce a pattern just as in filename
expansion. If the pattern matches a trailing portion of the
expanded value of PARAMETER, then the result of the expansion is
the value of PARAMETER with the shortest matching pattern (the '%'
case) or the longest matching pattern (the '%%' case) deleted. If
PARAMETER is '@' or '*', the pattern removal operation is applied
to each positional parameter in turn, and the expansion is the
resultant list. If PARAMETER is an array variable subscripted with
'@' or '*', the pattern removal operation is applied to each member
of the array in turn, and the expansion is the resultant list.
答案 1 :(得分:1)
${string%substring}
从$substring
后面删除$string
的最短匹配。
例如:
# Rename all filenames in $PWD with "TXT" suffix to a "txt" suffix.
# For example, "file1.TXT" becomes "file1.txt" . . .
SUFF=TXT
suff=txt
for i in $(ls *.$SUFF)
do
mv -f $i ${i%.$SUFF}.$suff
# Leave unchanged everything *except* the shortest pattern match
#+ starting from the right-hand-side of the variable $i . . .
done ### This could be condensed into a "one-liner" if desired.
${string%%substring}
从$substring
后面删除$string
的最长匹配。
stringZ=abcABC123ABCabc
# || shortest
# |------------| longest
echo ${stringZ%b*c} # abcABC123ABCa
# Strip out shortest match between 'b' and 'c', from back of $stringZ.
echo ${stringZ%%b*c} # a
# Strip out longest match between 'b' and 'c', from back of $stringZ.