42

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"  
jww
  • 90,984
  • 81
  • 374
  • 818
Arav
  • 4,603
  • 20
  • 71
  • 117
  • Possible duplicate of [Extract File Basename Without Path and Extension in Bash](http://stackoverflow.com/questions/2664740/extract-file-basename-without-path-and-extension-in-bash) – tripleee Aug 22 '16 at 10:40

7 Answers7

78

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
  • 429,241
  • 80
  • 483
  • 523
27

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
  • 307,646
  • 55
  • 250
  • 337
10

You can simply do:

base=$(basename "$fspec")
William Pursell
  • 190,037
  • 45
  • 260
  • 285
4

dirname "/usr/home/theconjuring/music/song.mp3" will yield /usr/home/theconjuring/music.

Berk Özbalcı
  • 2,696
  • 3
  • 17
  • 27
3

bash:

fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
1

Using bash "here string":

$ fspec="/exp/home1/abc.txt" 
$ tr  "/"  "\n"  <<< $fspec | tail -1
abc.txt
$ filename=$(tr  "/"  "\n"  <<< $fspec | tail -1)
$ echo $filename
abc.txt

The benefit of the "here string" is that it avoids the need/overhead of running an echo command. In other words, the "here string" is internal to the shell. That is:

$ tr <<< $fspec

as opposed to:

$ echo $fspec | tr
NetHead
  • 61
  • 1
  • 9
1
echo $fspec | tr "/" "\n"|tail -1
ghostdog74
  • 307,646
  • 55
  • 250
  • 337