Jason Bourne
Jason Bourne

Reputation:

ShellScript: Whats the diff between % and %% here?

I am a shell script newbie. I want to know the difference between

${var%pattern}

and

${var%%pattern}

Thanks

Upvotes: 0

Views: 261

Answers (2)

John Kugelman
John Kugelman

Reputation: 361849

From man bash:

${parameter%word}
${parameter%%word}

The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the "%" case) or the longest matching pattern (the "%%" case) deleted.

Here's an example of what the difference is:

$ VAR=abcdefabcdef
$ echo ${VAR%def*}
abcdefabc
$ echo ${VAR%%def*}
abc

Notice that there are two possible matches for def* at the end of $VAR: both "defabcdef" and just "def" match. With the "%" the shortest possible match for the pattern def* is deleted, so the trailing "def" is removed. With the "%%" the longest possible match is deleted, so "defabcdef" bites the dust.

Upvotes: 2

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74252

From man bash:

   ${parameter%word}
   ${parameter%%word}

Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded 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.

Upvotes: 0

Related Questions