Given a path to a file let say: /home/user1/archive.zip
Can someone tell me how can I remove the string archive.zip without using external binaries?
I know that:
${Path2File##*/}
Can give me the file name but I need the folder path for this one.
A guide to wildcard understanding or an explanation is welcomed as well.
Do
"${Path2File%\/*}"
or using external binaries
dirname "$Path2File" # Not desirable as you've mentioned already
Notes:
${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 deleted. /
has special meaning in shell parameter expansion we just escaped it ie \/
. The intention is to match the file basename ie
/example.zip
in /path/to/example.zip
and delete it.Reference:
Shell [ Parameter Expansion ]
The *
wildcard means any character will match. The ##
is removing the longest matching pattern from the parameter. For example:
$ a=/path/to/file
$ echo ${a##*t}
o/file
In this example, we said delete everything up to and including t
. It removed the /pat
as you would expect, but as it found a second t
it kept going. (A single #
would stop at the first t
).
A more useful example is to remove the path, as you have done, by matching up to and including the last /
.
$ echo ${a##*/}
file
The %
matches at the end of the string.
$ echo ${a%/*}
/path/to
This means delete from the rightmost slash /
and everything else *
.
The single %
looks for the shortest possible match. If we use %%
the match keeps looking all the way back to the start of the string and matches on the first character /
and gobbles the lot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With