Abbreviate long strings with dots using sed

Alec Jacobson

January 24, 2015

weblog/

My bash prompt lists the current directory name and I was bothered that if it's very long then it will take up the whole line. Here's a short sed command which will abbreviate any lines over 5+3+5=13 characters replacing the middle part with three dots:

echo \
"a very long directory name which will take up a whole line
short name
perfect name
just big name" | \
sed -e "s/\(.\{5\}\).\{3,\}\(.\{5,\}\)/\1...\2/"

produces

a ver... line
short name
perfect name
just ... name