views:

318

answers:

5

I have a variable which has the directory path along with 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"

+1  A: 

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
codaddict
A: 
William Pursell
A: 

bash:

fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"
Ignacio Vazquez-Abrams
A: 

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
ghostdog74
A: 
echo $fspec | tr "/" "\n"|tail -1