0

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

2

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
$ _
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"...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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