如何截断比给定长度更长的文本行?

问题描述

如何删除 x 个字符后的所有内容?例如,剪切15个字符后的所有内容,然后在其中添加...

This is an example sentence应该变成This is an exam...

解决方法

GnuTools head可以使用字符而不是行:

head -c 15 <<<'This is an example sentence'

尽管考虑到head -c只处理字节,所以这与UTF-8 umlaut ü之类的多字节字符不兼容。

Bash内置字符串索引工作:

str='This is an example sentence'
echo "${str:0:15}"

输出:

This is an exam

最后是与ksh,破折号,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"
,

您可以尝试:

echo 'some long string value' | sed 's/\(.\{15\}\).*/\1.../'

输出:

some long strin...
,

Awk也可以做到这一点:

$ echo 'some long string value' | awk '{print substr($0,1,15) "..."}'
some long strin...

在awk中,$0是当前行。 substr($0,15)$0中提取字符1到15。末尾的"..."附加了三个点。

,

使用Bash Shell扩展(无外部命令)

如果您不关心shell的可移植性,则可以在CUDA C++ shell expansions中使用多个不同的printf完全在Bash中完成此操作。这避免了炮轰外部命令。例如:

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…

您还可以通过这种方式遍历整个文件。给定一个文件,上面包含相同的句子(每行一个),则可以按以下方式使用builtin

while read; do
    trim "$REPLY"
done < example.txt

这种方法是否更快或更容易阅读尚有待商,,但它是100%Bash,无需分叉或子shell即可执行。

,

Todd实际上有一个很好的答案,但是我选择对其进行一些修改以使功能更好并删除不必要的部分:p

trim() {
    if (( "${#1}" > "$2" )); then
      echo "${1:0:$2}$3"
    else
      echo "$1"
    fi
}

在此版本中,较长的字符串上的附加文本由第三个参数选择,最大长度由第二个参数选择,文本本身由第一个参数选择。

不需要变量:)

,

使用cut

echo "This is an example sentence" | cut -b1-15
This is an exam