Using Linux and Bash, I have a script that outputs filenames with complete path, like this:
I would like the following output:
And I would like to get the filenames only. Tricky part is that I cannot predict how many levels deep the filename is located, so I cannot use standard Bash-kungfu to solve this...
I have no idea what this means, though. You set a new variable FILENAME that is $file with some magic applied. I do not understand the syntax and I am eager to learn more about this, since I find this very useful. Would you care to explain?
So the ##-case expands to the longest matching pattern deletion. Since the parameter is *, it removes all matching patterns in the array, until it has no matches left. You read in the entire pathname as an array which has a delimiter "/" and the final result is the filename only.
Am I right?
This would mean that /foo/bar/filename.pdf would result in filename.pdf, but if the input would have a trailing slash like so: /foo/bar/files/ it would return... nothing!
At times {file##/} can be use as an shell-builtin alternative for the command basename. But as you see, this scenario shows the difference between basename and {file##/}
Basename would have done the job also, it returned the exact same results I initially wanted. However, I ran into a situation the same day I got this answer, where I needed the parameter expansion, because I needed to find the last row in a ":"-delimited array. Basename would not have done the job.