percent symbol in Bash, what's it used for? [duplicate]
Asked Answered
S

1

58

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?

Skald answered 22/1, 2016 at 16:50 Comment(5)
gnu.org/software/bash/manual/html_node/… Third section from bottom.Mazard
Have a look here bash manipulating with strings percent signTowill
Also, the * is superfluous (always matches nothing when used after single %).Mazard
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.Steeplejack
As already noted in another comment, 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".Enhanced
S
115

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
Shampoo answered 22/1, 2016 at 16:55 Comment(1)
This answer is fine, although any interested reader coming here may want to compare it with this answer (which is slightly more elaborated I would say).Enhanced

© 2022 - 2024 — McMap. All rights reserved.