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.

/path/to/my/file

to just filename

file

This can be achieved by using basename command in linux.

Syntax

basename /path/to/my/file

Example:

basename /home/surendra/out.ogv

out.ogv

With SED:

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

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`
do
basename $i
done

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.




The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.