Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get path to file using bash parameter expansion

Tags:

bash

path

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.

like image 254
DarkXDroid Avatar asked Dec 19 '22 15:12

DarkXDroid


2 Answers

Do

"${Path2File%\/*}"

or using external binaries

dirname "$Path2File" # Not desirable as you've mentioned already

Notes:

  1. In the shell parameter expansion of type ${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.
  2. Since the / 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 ]

like image 52
sjsam Avatar answered Dec 26 '22 15:12

sjsam


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.

like image 29
Ian Petts Avatar answered Dec 26 '22 14:12

Ian Petts