Collapse directories in zsh prompt

384 Views Asked by At

I am using the following function to generate my zsh prompt:

_sudar_collapsed_wd() {
  echo $(pwd | perl -pe "
   BEGIN {
      binmode STDIN,  ':encoding(UTF-8)';
      binmode STDOUT, ':encoding(UTF-8)';
   }; s|^$HOME|~|g; s|/([^/])[^/]*(?=/)|/\$1|g
")
}

Basically this converts a path like /Users/sudar/dir1/dir2/dir3/dir4 into ~/D/c/d/d/d/dir4 by collapsing all parent directories except the current one.

But I don't want to collapse the last 3 directories in the path. So /Users/sudar/dir1/dir2/dir3/dir4 becomes ~/D/c/d/dir2/dir3/dir4

The actual substitution happens in this regular expression: s|/([^/])[^/]*(?=/)|/\$1|g.

How to change this regular expression, so that it doesn't substitute the last 3 directories in the path?

1

There are 1 best solutions below

0
On BEST ANSWER

You may use this,

s|^$HOME|~|g; s|/([^/])[^/]*(?=/[^/]*/[^/]*/)|/\$1|g

It checks that the match must be followed by atleast three forward slashes.

DEMO