Wednesday, January 31, 2024

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

Issue

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?

EDIT: I came up with this, but it's not POSIX compliant:

str="foobarSN10"
strlen=$(echo -n "$str" | wc -m)
delim=$'\u2026'
test $strlen -gt 9 && echo "$str" | sed 's/\(.\{4\}\).*\(.\{4\}\)/\1'$delim'\2/' || echo "$str"

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


Answered By - glenn jackman
Answer Checked By - Cary Denson (WPSolving Admin)