How to get the last part of dirname in Bash

无人久伴 提交于 2019-11-27 04:20:19

问题


Suppose I have a file /from/here/to/there.txt, and want to get only the last part of its dirname to instead of /from/here/to, what should I do?


回答1:


You can use basename even though it's not a file. Strip off the file name using dirname, then use basename to get the last element of the string:

dir="/from/here/to/there.txt"
dir="$(dirname $dir)"   # Returns "/from/here/to"
dir="$(basename $dir)"  # Returns just "to"



回答2:


The opposite of dirname is basename:

basename "$(dirname "/from/here/to/there.txt")"



回答3:


Using bash string functions:

$ s="/from/here/to/there.txt"
$ s="${s%/*}" && echo "${s##*/}"
to



回答4:


Pure BASH way:

s="/from/here/to/there.txt"
[[ "$s" =~ ([^/]+)/[^/]+$ ]] && echo "${BASH_REMATCH[1]}"
to



回答5:


Using Bash parameter expansion, you could do this:

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)

This is more efficient since no external commands are used.




回答6:


One more way

IFS=/ read -ra x <<<"/from/here/to/there.txt" && printf "%s\n" "${x[-2]}"



回答7:


An awk way of doing it would be:

awk -F'/' '{print $(NF-1)}' <<< "/from/here/to/there.txt"

Explanation:

  • -F'/' sets field separator as "/"
  • print the second last field $(NF-1)
  • <<< uses anything after it as standard input (wiki explanation)



回答8:


This question is something like THIS.

For solving that you can do:

DirPath="/from/here/to/there.txt"
DirPath="$(dirname $DirPath)"
DirPath="$(basename $DirPath)"

echo "$DirPath"

As my friend said this is possible as well:

basename `dirname "/from/here/to/there.txt"`

In order to get any part of your path you could do:

echo "/from/here/to/there.txt" | awk -F/ '{ print $2 }'
OR
echo "/from/here/to/there.txt" | awk -F/ '{ print $3 }'
OR
etc


来源:https://stackoverflow.com/questions/23162299/how-to-get-the-last-part-of-dirname-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!