Wednesday, October 24, 2012

Linux command/shell script to extract filename form a path

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




0 comments:

Post a Comment