53

I have a filename which ends with .zip and I wanted just the filename without zip. Here I found a trick in bash.

$f="05 - Means-End Analysis Videos.zip"
$echo "${f%*.zip}"
05 - Means-End Analysis Videos

What is happening here? How come %*.zip is removing my extension?

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
  • 3
    https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html Third section from bottom. – Jeff Y Jan 22 '16 at 16:54
  • 1
    Have a look here [bash manipulating with strings percent sign](http://stackoverflow.com/questions/16444004/bash-manipulating-with-strings-percent-sign) – mauro Jan 22 '16 at 16:57
  • 6
    Also, the `*` is superfluous (always matches nothing when used after single `%`). – Jeff Y Jan 22 '16 at 17:00
  • note that another usage of the `%` character in bash is if a program such as `vim` is suspended with `ctrl-z`, then the `%vim` command resumes it, like `fg`. – xdavidliu Nov 30 '19 at 23:27
  • As already noted in [another comment](https://stackoverflow.com/q/34951901#comment57635748_34951901), the `*` does not make much sense. The snippet `"${f%*.zip}"` means keep the content of `f`, but remove the last occurrence of `.zip`. * ~ * ~ * So in `"05 - Means-End Analysis Videos.zip"` simply cut out `.zip` to get `"05 - Means-End Analysis Videos"`. – Henke Feb 08 '22 at 13:57

1 Answers1

106

Delete the shortest match of string in $var from the beginning:

${var#string}

Delete the longest match of string in $var from the beginning:

${var##string}

Delete the shortest match of string in $var from the end:

${var%string}

Delete the longest match of string in $var from the end:

${var%%string}

Try:

var=foobarbar
echo "${var%b*r}"
> foobar
echo "${var%%b*r}"
> foo
pfnuesel
  • 14,093
  • 14
  • 58
  • 71
  • 4
    This answer is fine, although any interested reader coming here may want to compare it with [this answer](https://stackoverflow.com/a/25536935) (which is slightly more elaborated I would say). – Henke Feb 08 '22 at 14:14