Linux 取shell中文件夹路径的最后一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10654135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Take the last part of the folder path in shell
提问by Lukap
If you type pwd you get something like:
如果你输入 pwd 你会得到类似的东西:
/home/username/Desctop/myfolder/
/home/username/Desctop/myfolder/
How to take the last part? The myfolder
path.
最后一部分怎么打?该myfolder
路径。
This must be simple but I couldn't find easy solution in shell. I know how to take care of this in java but not in shell.
这一定很简单,但我在 shell 中找不到简单的解决方案。我知道如何在 java 中处理这个问题,但在 shell 中不知道如何处理。
thanks
谢谢
采纳答案by andyras
You're right--it's a quick command:
你是对的——这是一个快速命令:
basename "$PWD"
回答by Eduardo Ivanec
You can use basename
for that, provided the last part is indeed a directory component (not a file):
您可以使用basename
它,前提是最后一部分确实是目录组件(不是文件):
$ basename /home/username/Desctop/myfolder/
myfolder
回答by alex
To extract the last part of a path, try using basename
...
要提取路径的最后一部分,请尝试使用basename
...
basename $(pwd);
回答by octopusgrabbus
In Linux, there are a pair of commands, dirname
and basename
. dirname
extracts all but the last part of a path, and basename
extracts just the last part of a path.
在 Linux 中,有一对命令,dirname
和basename
. dirname
提取除路径最后一部分之外的所有内容,并basename
仅提取路径的最后一部分。
In this case, using basename
will do what you want:
在这种情况下, usingbasename
将执行您想要的操作:
basename $(pwd)
basename $(pwd)
回答by Jens
Using basename $(pwd)
are two useless and expensive forks.
使用的basename $(pwd)
是两个无用且昂贵的叉子。
echo ${PWD##*/}
should do the trick completely in the shell without expensive forks (snag: for the root directory this is the empty string).
应该完全在 shell 中完成这个技巧,而无需昂贵的分叉(障碍:对于根目录,这是空字符串)。
回答by konsolebox
function basename {
shopt -s extglob
__=${1%%+(/)}
[[ -z $__ ]] && __=/ || __=${__##*/}
}
basename "$PWD"
echo "$__"