Extract directory path and filename

2020-05-14 14:31发布

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"  

标签: shell unix
7条回答
Rolldiameter
2楼-- · 2020-05-14 14:55

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
查看更多
手持菜刀,她持情操
3楼-- · 2020-05-14 14:57

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
查看更多
啃猪蹄的小仙女
4楼-- · 2020-05-14 15:00

bash:

fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"
查看更多
Explosion°爆炸
5楼-- · 2020-05-14 15:01

You can simply do:

base=$(basename "$fspec")
查看更多
Melony?
6楼-- · 2020-05-14 15:05

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
查看更多
做自己的国王
7楼-- · 2020-05-14 15:07

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

查看更多
登录 后发表回答