我有这个代码:
get_base() { echo "${1##*/}"; }
在我们有 1 个或更多之前,这可以正常工作 斜杠
我找到了解决方法,但是
问题是我们需要启用 extglob
,而我不需要
想要那个:
ari@ari-gentoo ~ % x='/home/ari///'
ari@ari-gentoo ~ % echo "${x%%+(/)}"
/home/ari
然后我们可以 obv 将它保存到一个 tmp var 并运行 basename 替换它
无论如何,我的问题是,有没有合适的方法来做到这一点 而且它仍然很快(意味着没有调用外部命令 因为这个函数被调用了很多)没有 需要启用任何花哨的功能吗?
提前感谢您的回答:)
问答
no as all of those solutions either use commands or have a substitution expression that only strips the last slash, not multiples :) (e.g. /home/ari/// with expr ${x%/} would become only /home/ari// when it needs to be /home/ari)
- “正确”是什么意思
By proper I mean 'achieved without enabling extglob or any other fancy features'
最佳答案
这是一种方法:
get_base() {
set -- "${1%"${1##*[!/]}"}"
printf '%s\n' "${1##*/}"
}
$ get_base /home/oguz//
oguz
$ get_base /root
root
$ get_base /
$ get_base .bash_history
.bash_history
关于linux - 在 bash 中获取目录或文件的基本名称的快速且正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74089893/