Extract the last directory of a pwd output

痞子三分冷 提交于 2019-11-30 12:42:01

问题


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.


回答1:


Are you looking for basename or dirname?

Something like

basename "`pwd`"

should be what you want to know.

If you insist on using sed, you could also use

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



回答2:


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




回答3:


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

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




回答4:


Using awk:

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


来源:https://stackoverflow.com/questions/1744595/extract-the-last-directory-of-a-pwd-output

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