【问题标题】:How to add last 10 character after truncating the string如何在截断字符串后添加最后 10 个字符
【发布时间】:2022-01-22 02:02:51
【问题描述】:

我正在尝试用多行来做到这一点

words="
What do you think about the kitten outside?
The tattered work gloves speak of the many hours of hard labor he endured throughout his life.
Hello
Hi
"

我使用cut -c -17 截断它。
我正在尝试像这样输出它:

What do you think...n outside?
The tattered work... his life.
Hello
Hi

对不起,我仍然是 bash 脚本的菜鸟...谢谢

【问题讨论】:

  • 最简单的方法是从words一次读取一行,while read line; do ... done <<< $words,然后您可以简单地使用参数扩展为前17个索引"${line:0:17}",然后为"${line: -10}"索引最后 10 个。(注意:" -10" 之前的空格是必需的,或者用括号括起来 "(-10)")您需要在 ${#line} 上添加长度检查,并且只输出最后 10 个(或less) 如果长度大于 17。
  • @David C. Rankin 我忘了说,我也用过那个循环,但是在阅读数百行句子时似乎太慢了
  • 好吧,如果您发现自己试图将数百行存储为单个变量——您需要以其他方式存储它们。如果从文件中读取,请使用 readarray(与 mapfile 同义)将文件读入索引数组。变量将存储您告诉他们的内容,但是(不查看 bash 源代码),我怀疑将数百行输入关联为单个变量可能会产生额外的开销。
  • @NebDev 听起来您正在寻找的解决方案是基于意见的。

标签: bash truncate


【解决方案1】:

从注释继续,你可以单独阅读每一行,并计算出后缀长度(如果小于10)如下

#!/bin/bash

words="
What do you think about the kitten outside?
The tattered work gloves speak of the many hours of hard labor he endured throughout his life.
Hello
Hi
"

while read line; do                           # loop reading each line
  len=${#line}                                # get line length
  [ "$len" -eq 0 ] && continue                # if zero len, get next line
  suffix=0                                    # set suffix length 0
  [ "$len" -gt 17 ] && suffix=$((len - 17))   # get max suffix length
  [ "$suffix" -ge 10 ] && suffix=10           # if > 10, set to 10
  printf "%s" "${line:0:17}"                  # output first 17 chars
  if [ "$suffix" -gt 0 ]; then                # if suffix > 0, output
    printf "...%s\n" "${line: -$suffix}"
  else                                        # otherwise output \n
    printf "\n"
  fi
    
done <<< $words        # feed loop with "herestring" from words

注意:[ ... ] &amp;&amp; do_something 只是 if [ ... ]; then do_something; fi 的简写。您也可以对|| 使用相同的速记。但是,avoid[ ... ] &amp;&amp; do_something || do_something_else 链接为|| 如果第一部分因任何原因失败,则将被执行。 (所以它不是if [...]; then ... else; fi 的捷径)

使用/输出示例

$ ./prefixsuffix.sh
What do you think...n outside?
The tattered work... his life.
Hello
Hi

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多