bashsedtrailing-newline

Truncating "wrapping" long string outputs with prefix, appends new line at the bottom of each dump of the hold space


I'm trying to prefix console outputs, while truncating long string outputs to a maximum of 60 characters. (Preventing long lines from bleeding over and breaking the prefix)

How come...

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

...is appending a new (un-prefixed) line below each dump of the hold space? How can I stop this behavior, or at least append a prefix to it?

Output:

║      

║      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.

║

Solution

  • You need to replace the whole line with its first 60 characters.

    sed -e 's/^\(.\{0,60\}\).*/'"$esc"'[35m║      \1/'
    #          ~~         ~~^^                    ~~
    #           1          1 2                     3