help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to trim a path and just leave last n levels?


From: Andreas Kusalananda Kähäri
Subject: Re: How to trim a path and just leave last n levels?
Date: Wed, 15 Apr 2020 09:39:08 +0200

On Tue, Apr 14, 2020 at 09:22:17AM -0500, Peng Yu wrote:
> Hi,
> 
> basename just leaves the last level in a path. Is there a good way to
> leave the last two levels or the last n levels of a path? Thanks.
> 
> -- 
> Regards,
> Peng

What you're asking about is the equivalent of zsh's %d (or %/) prompt
format string which could be used for this (well, for the current
working directory at least):

$ pwd
/tmp/shell.DAd5JbZC/dir1/dir2
$ print -P '%2d'
dir1/dir2

The naive way would be to remove the prefix string from the path that
matches everything but the last two directory level:

$ pwd
/tmp/shell.DAd5JbZC/dir1/dir2
$ printf '%s\n' "${PWD#${PWD%/*/*}/}"
dir1/dir2

This would only work if the path contains at least two levels though,
and hard-codes the number of levels that you'd want leave.


-- 
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden

.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]