Finding last row

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...

Add this line to the script

FILENAME=${file##*/}

where file would hold contain the values

/foo/bar/filename.pdf
/foo/bar/filename with space.pdf
/foo/filename.txt 

one at a time.

And FILENAME would hold filename.pdf filename with space.. et al.

vino

Now that worked perfectly!

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?

Dare to start out with the man pages ? :stuck_out_tongue:

Check out the section Parameter Expansion under man sh
and the section Parameters under man ksh

-vino

Found it! I wanted to read more about this, but did not realize this was a shell built-in option, so did not think of man bash (in my case)...

Appreciate the help!

I believe I understand what happened...

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!

True.

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##/}

vino

Just so others can benefit from this thread:

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.