在 shell 脚本中,当参数长度超过 9 到总长度 9(前 4 个和后 4 个字符,中间有 UTF-8 省略号)时,我想截断参数。对我来说,在中间截断它至关重要,因为第一部分是名称,而最后一部分通常包含一个数字,有助于识别它所命名的事物。
foobarSN9
应该变成 foobarSN9
foobarSN10
应该变成 foob…SN10
如何用尽可能少的代码来完成符合 POSIX 标准的操作?
在 dash
中测试trunc() {
if [ "${#1}" -le 9 ]; then
echo "$1"
else
tmp=${1%????} # remove the last 4 chars
suffix=${1#$tmp} # keep the last 4 chars
tmp=${1#????} # remove the first 4 chars
prefix=${1%$tmp} # keep the first 4 chars
echo "${prefix}…${suffix}"
fi
}
$ trunc "hello"
hello
$ trunc "hello world"
hell…orld