48

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
  • 97,681
  • 90
  • 411
  • 885
Arav
  • 4,957
  • 23
  • 77
  • 123
  • 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

87

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
  • 445,704
  • 82
  • 492
  • 529
33

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
  • 327,991
  • 56
  • 259
  • 343
  • Thanks a lot for how to get the path and file names using Bash string manipulation! I’ve been searching for these precise cases for hours! – breversa Mar 15 '23 at 09:29
14

You can simply do:

base=$(basename "$fspec")
William Pursell
  • 204,365
  • 48
  • 270
  • 300
4

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

Berk Özbalcı
  • 3,016
  • 3
  • 21
  • 27
3

bash:

fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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
  • 71
  • 1
  • 10
1
echo $fspec | tr "/" "\n"|tail -1
ghostdog74
  • 327,991
  • 56
  • 259
  • 343