...
。
This is an example sentence
应该变成This is an exam...
gnutools
head
head -c 15 <<<'This is an example sentence'
head -c
仅处理字节,因此这与诸如UTF-8 umlaut之类的多字角色不相容。式内置字符串索引工作:
ü
输出:
str='This is an example sentence'
echo "${str:0:15}"
最终与KSH,Dash,Zsh一起使用的东西……:
This is an exam
以编程方式:
printf '%.15s\n' 'This is an example sentence'
如果您使用的是bash,则可以直接将
n=15
printf '%.*s\n' $n 'This is an example sentence'
输出分配给变量,并保存一个子壳呼叫:
printf
使用
trim_length=15
full_string='This is an example sentence'
printf -v trimmed_string '%.*s' $trim_length "$full_string"
:cut
echo "This is an example sentence" | cut -c1-15
This is an exam
cut(1)
使用
-b, --bytes=LIST
select only these bytes
-c, --characters=LIST
select only these characters
:sed
echo 'some long string value' | sed 's/\(.\{15\}\).*/\1.../'
该解决方案的优点是,短字符串不会添加tail:
some long strin...
输出:
...
因此,这是所有大小输出的解决方案。wawk也可以完成此操作:
echo 'short string' | sed 's/\(.\{15\}\).*/\1.../'
中awk,
short string
是当前的线。 $ echo 'some long string value' | awk '{print substr($0, 1, 15) "..."}'
some long strin...
substr($0, 1, 15)
todd实际上有一个很好的答案,但是我选择将其更改一些以使功能更好并删除不必要的部分:p
$0
在此版本中,较长字符串上的附加文本由第三个参数选择,最大长度由第二个参数选择,文本本身由第一个参数选择。
不需要变量:)如果您不关心外壳可移植性,则可以在Bash中使用许多不同的shell扩展在bash中进行此操作。这样可以避免向外部命令弹出。例如:
"..."
您还可以通过这种方式循环整个文件。给定一个包含上面相同句子的文件(每行),您可以使用
readin内置的默认
reply变量
如下:trim() {
if (( "${#1}" > "$2" )); then
echo "${1:0:$2}$3"
else
echo "$1"
fi
}
将省略号附加到长线上trim () {
local str ellipsis_utf8
local -i maxlen
# use explaining variables; avoid magic numbers
str="$*"
maxlen="15"
ellipsis_utf8=$'\u2026'
# only truncate $str when longer than $maxlen
if (( "${#str}" > "$maxlen" )); then
printf "%s%s\n" "${str:0:$maxlen}" "${ellipsis_utf8}"
else
printf "%s\n" "$str"
fi
}
trim "This is an example sentence." # This is an exam…
trim "Short sentence." # Short sentence.
trim "-n Flag-like strings." # Flag-like strin…
trim "With interstitial -E flag." # With interstiti…
while read; do
trim "$REPLY"
done < example.txt
awk