planetp
planetp

Reputation: 16095

How to extract last directory in path in Zsh?

Say I have a variable containing path to a directory (with a trailing slash):

dir="path/to/dir/"

How can I extract the last directory (i.e. "dir") using Zsh's parameter expansion? I would like to avoid calling external programs (like sed).

Upvotes: 0

Views: 968

Answers (2)

chepner
chepner

Reputation: 531490

Parameter expansions in zsh can use csh-style history modifiers; in this case, you can use :t

   t      Remove  all leading pathname components, leaving the tail.  This
          works like `basename'.
% dir="path/to/dir/"
% print $dir
path/to/dir/
% print $dir:t
dir

Upvotes: 2

planetp
planetp

Reputation: 16095

In Zsh, you can nest expansions. So this works:

$ dir="path/to/dir/"
$ echo "${${dir%/}##*/}"
dir

Upvotes: 0

Related Questions