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.
foobarSN9should turn intofoobarSN9foobarSN10should turn intofoob…SN10
How can this be done POSIX compliant in as little code as possible?
>Solution :
Tested in dash
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