How to get file-name from a path or a URL

Q. What is the good and simple way to extract a filename from complete path in Linux?

Some times it's handy to get just filename instead of filename with path as shown below.


to just filename


This can be achieved by using basename command in linux.


basename /path/to/my/file


basename /home/surendra/out.ogv


With SED:

echo "/home/surendra/out.ogv" | sed -r 's_(/.*/)(.*)_2_g'

What to learn basics of SED?, click here
It is that much simple.

How about getting all the filenames from a given set of paths which are stored in a file or a command output.

Script to extract filenames from path

for i in `cat /abc/completefilenames.txt`
basename $i

Let me explain the above code. for loop will take one by one line from /abc/completefilenames.txt file and feed that one to basename command, which intern will give you just the file name.

Related concept:   Shell scripting Variables in Linux/Unix