Reputation: 695
What does the following regex mean?
fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"
I know what it does, but not how it does? Fetching fname is not clear to me.
Please explain.
Upvotes: 3
Views: 62
Reputation: 1037
Below is the explanation from bash documentation.
${parameter#word}
${parameter##word}
The word is expanded to produce a pattern just as in pathname
expansion. If the pattern matches the beginning of the 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.
As per the above explanation, In your example word=*/ which means zero (or) any number of characters ending with /.
bash-3.2$fspec="/exp/home1/abc.txt"
bash-3.2$echo "${fspec##*/}" # Here it deletes the longest matching pattern
# (i.e) /exp/home1/
# Output is abc.txt
bash-3.2$echo "${fspec#*/}" # Here it deletes the shortest matching patter
#(i.e) /
# Output is exp/home1/abc.txt
bash-3.2$
Upvotes: 1
Reputation: 289745
The ${var##*/}
syntax strips everything up to the last /
.
$ fspec="/exp/home1/abc.txt"
$ echo "${fspec##*/}"
abc.txt
In general, ${string##substring}
strips the longest match of $substring
from front of $string
.
For further reference you can for example check Bash String Manipulation with several explanations and examples.
Upvotes: 4