Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to truncate a String in the middle with ellipsis POSIX compliant?

In a shell script I would like to truncate an argument when it exceeds a length of 9 to a total length of 9 (first 4 and last 4 characters with an UTF-8 ellipsis in between). It’s crucial to me to truncate it in the middle, since the first part is the name, while the last part often includes a number that helps to identify the thing it names.

  • foobarSN9 should turn into foobarSN9
  • foobarSN10 should turn into foob…SN10

How can this be done POSIX compliant in as little code as possible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Tested in

trunc() {
    if [ "${#1}" -le 9 ]; then
        echo "$1"
    else
        printf '%s…%s\n' "${1%%"${1#????}"}" "${1##"${1%????}"}"
    fi
}
$ trunc "hello"
hello
$ trunc "hello world"
hell…orld
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading