Extract the last directory of a pwd output

2019-02-05 19:33发布

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.

标签: bash unix pwd
4条回答
走好不送
2楼-- · 2019-02-05 19:56

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

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

查看更多
祖国的老花朵
3楼-- · 2019-02-05 20:01

Using awk:

pwd | awk -F/ '{print $NF}'
查看更多
三岁会撩人
4楼-- · 2019-02-05 20:05

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

查看更多
\"骚年 ilove
5楼-- · 2019-02-05 20:12

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#.*/##'
查看更多
登录 后发表回答