Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract directory path and filename

Tags:

shell

unix

I have a variable which has the directory path, along with the file name. I want to extract the filename alone from the Unix directory path and store it in a variable.

fspec="/exp/home1/abc.txt"   
like image 437
Arav Avatar asked Mar 29 '10 06:03

Arav


People also ask

How do I get filename and path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.

How do I separate the filename and path in Python?

split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that. In the above example 'file. txt' component of path name is tail and '/home/User/Desktop/' is head.

How can I extract the folder path from file path in Python?

Use os. path. dirname() to get the directory folder (name) from a path string.


2 Answers

Use the basename command to extract the filename from the path:

[/tmp]$ export fspec=/exp/home1/abc.txt  [/tmp]$ fname=`basename $fspec` [/tmp]$ echo $fname abc.txt 
like image 141
codaddict Avatar answered Sep 28 '22 15:09

codaddict


bash to get file name

fspec="/exp/home1/abc.txt"  filename="${fspec##*/}"  # get filename dirname="${fspec%/*}" # get directory/path name 

other ways

awk

$ echo $fspec | awk -F"/" '{print $NF}' abc.txt 

sed

$ echo $fspec | sed 's/.*\///' abc.txt 

using IFS

$ IFS="/" $ set -- $fspec $ eval echo \${${#@}} abc.txt 
like image 42
ghostdog74 Avatar answered Sep 28 '22 16:09

ghostdog74