我正在尝试为控制台输出添加前缀,同时将长字符串输出截断为最多 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.
║
您需要将整行替换为前 60 个字符。
sed -e 's/^\(.\{0,60\}\).*/'"$esc"'[35m║ \1/'
# ~~ ~~^^ ~~
# 1 1 2 3
1
记住前 60 个字符,2
与其余部分匹配,3
输出记住的部分。您的替换字符串明确表示在每 0 到 60 个字符后添加一个换行符,这就是 sed 正在做的事情,然后它像往常一样在所有输出的末尾打印一个终止换行符,这就是导致空行的原因出现。使用较小的输入和较小的范围更容易看到:
$ echo '1234' | sed 's/.\{0,2\}/<&>\n/g'
<12>
<34>
$
$ echo '12345' | sed 's/.\{0,2\}/<&>\n/g'
<12>
<34>
<5>
$
解决问题的方法有多种,但您似乎试图换行(又称折叠)线而不是截断它们,所以请尝试以下方法:
fold -s -w60 | sed "s/^/${esc}[35m║ /"
这里使用的是我认为你的原始输出
sudo apt upgrade 2>&1 >&1
可能看起来像的输入:
$ cat file
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 upgraded.
$ cat file | fmt -s -w60 | sed "s/^/${esc}[35m║ /"
║ 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
║ upgraded.
请注意,
fold
在空白处分割输入(如果可以的话),而你的 sed 命令会在单词中间截断行,这会产生更混乱的输出。