bash 提取密码输出的最后一个目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1744595/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:41:43  来源:igfitidea点击:

Extract the last directory of a pwd output

bashunixpwd

提问by Siou

How do I extract the last directory of a pwd output? I don't want to use any knowledge of how many levels there are in the directory structure. If I wanted to use that, I could do something like:

如何提取密码输出的最后一个目录?我不想使用有关目录结构中有多少级别的任何知识。如果我想使用它,我可以这样做:

> pwd
/home/kiki/dev/my_project
> pwd | cut -d'/' -f5
my_project

But I want to use a command that works regardless of where I am in the directory structure. I assume there is a simple command to do this using awk or sed.

但我想使用一个无论我在目录结构中的位置都能工作的命令。我假设有一个简单的命令可以使用 awk 或 sed 来执行此操作。

回答by mihi

Are you looking for basenameor dirname?

您是在寻找basename还是dirname

Something like

就像是

basename "`pwd`"

should be what you want to know.

应该是你想知道的。

If you insist on using sed, you could also use

如果你坚持使用sed,你也可以使用

pwd | sed 's#.*/##'

回答by Teddy

If you want to do it completely within a bash script without running any external binaries, ${PWD##*/}should work.

如果你想在不运行任何外部二进制文件的情况下完全在 bash 脚本中完成它,${PWD##*/}应该可以。

回答by CenterOrbit

Should work for you: pwd | rev | cut -f1 -d'/' - | rev

应该为你工作: pwd | rev | cut -f1 -d'/' - | rev

Reference: https://stackoverflow.com/a/31728689/663058

参考:https: //stackoverflow.com/a/31728689/663058

回答by Christopher Pickslay

Using awk:

使用 awk:

pwd | awk -F/ '{print $NF}'