egg*_*elf 65 bash shell dirname
假设我有一个文件/from/here/to/there.txt,并且只想获取其dirname的最后一部分to而不是/from/here/to,我该怎么办?
Dav*_* W. 96
basename即使它不是文件,您也可以使用.使用剥离文件名dirname,然后使用basename获取字符串的最后一个元素:
dir="/from/here/to/there.txt"
dir="$(dirname $dir)"   # Returns "/from/here/to"
dir="$(basename $dir)"  # Returns just "to"
Run Code Online (Sandbox Code Playgroud)
        tha*_*guy 19
相反的dirname是basename:
basename "$(dirname "/from/here/to/there.txt")"
Run Code Online (Sandbox Code Playgroud)
        jay*_*ngh 19
使用bash字符串函数:
$ s="/from/here/to/there.txt"
$ s="${s%/*}" && echo "${s##*/}"
to
Run Code Online (Sandbox Code Playgroud)
        使用 Bash参数扩展,你可以这样做:
path="/from/here/to/there.txt"
dir="${path%/*}"       # sets dir      to '/from/here/to' (equivalent of dirname)
last_dir="${dir##*/}"  # sets last_dir to 'to' (equivalent of basename)
Run Code Online (Sandbox Code Playgroud)
由于不使用外部命令,因此效率更高。
一种awk方法是:
awk -F'/' '{print $(NF-1)}' <<< "/from/here/to/there.txt"
Run Code Online (Sandbox Code Playgroud)
解释:
-F'/'将字段分隔符设置为“/”$(NF-1)<<<使用其后的任何内容作为标准输入(维基解释)