1

How to get from this prompt

~/this/is/a-very-very-long-directory-name/dir

to this

~/this/is/a-ver...name/dir

in a bash prompt?

So shorten directory names longer than nn (20+) characters to something like xxxx...xxxx

note for possible duplicate: I want to shorten a long dir name, not a long path/to/dir

Ju Tutt
  • 123
  • 1
  • 7
  • Similar: https://unix.stackexchange.com/q/55930/117549 – Jeff Schaller Dec 27 '18 at 15:00
  • 5
    Possible duplicate of [bash prompt with abbreviated current director including dot files?](https://unix.stackexchange.com/questions/55930/bash-prompt-with-abbreviated-current-director-including-dot-files) – Daniele Santi Dec 27 '18 at 15:09
  • 1
    I want to shorten a long dir name, not a long path – Ju Tutt Dec 27 '18 at 15:57
  • Hello @JuTutt. The possible duplicate also shortens a directory name, not a path. That being said, I think your question is more general than the linked one -- and also the answer is more complex (pre and post match). That's why I'm opposing the duplicate vote. – Sebastian Dec 28 '18 at 21:15

2 Answers2

4

You'll need to use something like , bash doesn't have any builtin method.

 d='~/this/is/a-very-very-long-directory-name/with_another_very_long_name/and-here-is-yet-another-one'
# or, d=$(pwd)
e=$( echo "$d" | sed -E 's#([^/]{4})[^/]{13,}([^/.]{3})#\1...\2#g' )
echo "$e"
~/this/is/a-ve...ame/with...ame/and-...one

On the other hand, you may want to throw a newline into your prompt. I use something like this:

PS1='\u@\h:\w\n\$ '

which would look like

jackman@myhost:~/this/is/a-very-very-long-directory-name/with_another_very_long_name/and-here-is-yet-another-one
$ _
glenn jackman
  • 84,176
  • 15
  • 116
  • 168
0

With shell's "parameter expansion", try

d='~/this/is/a-very-very-long-directory-name/with_another_very_long_name/and-here-is-yet-another-one'
IFS=/
for DIR in $d
  do    [ ${#DIR} -gt 8 ] &&    { TMP=${DIR%%${DIR#????}}
                                  DIR=$TMP...${DIR##${DIR%????}}
                                }
        NEW="$NEW${NEW:+/}$DIR"
  done
echo "$NEW"
~/this/is/a-ve...name/with...name/and-...-one

Save and restore IFS if need be. Running in a subshell won't work as you want to access the NEW variable afterwards (unless you use "command substitution"...).

RudiC
  • 8,889
  • 2
  • 10
  • 22