shell脚本中%和%%有什么区别?

时间:2018-05-22 04:26:55

标签: linux bash shell scripting

在bash脚本中,当t="hello.txt"两者

${t%%.txt}${t%.txt}返回"hello"

同样适用于${t##*.}${t#*.}返回"txt"

它们之间有区别吗?他们是如何运作的?

2 个答案:

答案 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.