截断带前缀的长字符串输出,在保留空间的每个转储的底部附加新行

问题描述 投票:0回答:1

我正在尝试为控制台输出添加前缀,同时将长字符串输出截断为最多 60 个字符。 (防止长线溢出并破坏前缀)

怎么会...

esc=$(printf '\033')
sudo apt upgrade 2>&1 >&1 | sed -e "s/.\{0,60\}/${esc}[35m║      &\n/g"

...是否在保留空间的每个转储下方附加一个新的(无前缀)行?我怎样才能阻止这种行为,或者至少为其添加一个前缀?

输出:

║      

║      WARNING: apt does not have a stable CLI interface. Use with 
║      caution in scripts.

║      

║      Reading package lists...

║      Building dependency tree...

║      Reading state information...

║      Calculating upgrade...

║      0 upgraded, 0 newly installed, 0 to remove and 0 not upgrade
║      d.

║
bash sed trailing-newline
1个回答
0
投票

您需要将整行替换为前 60 个字符。

sed -e 's/^\(.\{0,60\}\).*/'"$esc"'[35m║      \1/'
#          ~~         ~~^^                    ~~
#           1          1 2                     3
  • 1
    记住前 60 个字符,
  • 2
    与其余部分匹配,
  • 3
    输出记住的部分。
© www.soinside.com 2019 - 2024. All rights reserved.