如何删除指定数量的字符后的所有内容?例如,删除15个字符后的所有内容并添加...
。
This is an example sentence
应该变成 This is an exam...
如何删除指定数量的字符后的所有内容?例如,删除15个字符后的所有内容并添加...
。
This is an example sentence
应该变成 This is an exam...
GnuTools的head
可以使用字符而非行:
head -c 15 <<<'This is an example sentence'
尽管如此,请注意 head -c
只处理字节,因此它与多字节字符(如UTF-8变音符号 ü
)不兼容。
Bash内置字符串索引功能可用:str='This is an example sentence'
echo "${str:0:15}"
输出:
This is an exam
最后,这是适用于ksh、dash、zsh等的解决方案:
printf '%.15s\n' 'This is an example sentence'
即使是通过编程:
n=15
printf '%.*s\n' $n 'This is an example sentence'
如果你在使用Bash,你可以直接将printf
的输出赋值给一个变量,并通过以下方式避免调用子shell:
trim_length=15
full_string='This is an example sentence'
printf -v trimmed_string '%.*s' $trim_length "$full_string"
使用 sed
:
echo 'some long string value' | sed 's/\(.\{15\}\).*/\1.../'
输出:
some long strin...
这种解决方案的优点是短字符串不会添加...
尾随:
echo 'short string' | sed 's/\(.\{15\}\).*/\1.../'
输出:
short 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
Awk也可以实现这个目的:
$ echo 'some long string value' | awk '{print substr($0, 1, 15) "..."}'
some long strin...
$0
代表当前行。substr($0, 1, 15)
提取$0
中1到15个字符。结尾的"..."
添加三个点号。Todd 提供了不错的答案,但我稍作改动,使函数更好并去除了不必要的部分 :p
trim() {
if (( "${#1}" > "$2" )); then
echo "${1:0:$2}$3"
else
echo "$1"
fi
}
trim(){ printf '%.*s' $2 "$1";}
。如果你只想在Bash中使用并且速度更快,可以这样做:printf -v trimmed_string '%.*s' $trim "$full_string"
。 - Léa Gristrim "My Long String" <maxLen> "..."
- automorphictrim () {
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
${str:0:15}
非常好,谢谢! - Garret Wilson