Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I like customizing my PS1 prompt and including the current directory.

I also have several other items such as time, user, git branch and the like, i.e.

enter image description here

However one problem is that when my current directory is many layers 'deep' such as /home/durrantmm/Dropnot/webs/rails_apps/linker/app/views there is too much text. (btw I carriage return at the end within my PS1 prompt setting anyway so my actual $ is back on the left, that is not the issue here).

So I have a solution for that, to use this for the location part:

LOCATION='\033[01;34m\]`pwd | sed "s#\(/[^/]\+/[^/]\+/[^/]\+/\).*\(/[^/]\+/[^/]\+\)/\?#\1_\2#g"`'

not pretty, but it does the job and I then combine it with the other stuff (not shown, not needed here) and I get "first 3 levels _ last two levels" for the directories, i.e.

enter image description here

Unfortunately though on my mac the sed part isn't working correctly and I get:

enter image description here
[this is actually from my Linux machine, I faked it to show what it looks like on my mac in case you are wondering).

How can I get the 3_2 format for the current directory on my mac ?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

The \+ and \? parts of your sed command are GNU extensions - POSIX compatible sed cannot use these aspects of extended regex at all. Instead you can use \{1,\} and \{0,1\}. Try this:

LOCATION='\033[01;34m\]`pwd |
  sed "s#\(/[^/]\{1,\}/[^/]\{1,\}/[^/]\{1,\}/\).*\(/[^/]\{1,\}/[^/]\{1,\}\)/\{0,1\}#\1_\2#g"`'

For more information on this see - http://pubs.opengroup.org/onlinepubs/009696699/utilities/sed.html and http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html.

Alternatively, you can enable extended regular expressions on OSX sed using -E. With this you could do:

LOCATION='\033[01;34m\]`pwd |
  sed -E "s#\(/[^/]+/[^/]+/[^/]+/\).*\(/[^/]+/[^/]+\)/?#\1_\2#g"`'

However, this won't work on GNU sed (it uses -r for this). Using a POSIX solution will give better portability.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.