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"
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.
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.
Use os. path. dirname() to get the directory folder (name) from a path string.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With