gpt4 book ai didi

Bash 不应将颜色代码计为可见字符

转载 作者:行者123 更新时间:2023-11-29 09:28:34 29 4
gpt4 key购买 nike

我正在使用 fold 来包装我的输入文件。我注意到一些彩色线条较短。我发现 bash 将颜色代码计为字符,即使不可见也是如此。示例:

$ text="\e[0;31mhello\e[0m"; echo -e "$text - lenght ${#text}"
hello - lenght 18
$ text="hello"; echo -e "$text - lenght ${#text}"
hello - lenght 5

其他不可见字符也会发生这种情况:

$ text="a\bb\bc"; echo -e "$text - lenght ${#text}"
c - lenght 7

是否可以改变这种行为?我希望 coreutils 程序(例如 bashfold)可以只计算可见字符。

最佳答案

这不是您问题的完整解决方案,但重要的是要知道 bash 不处理文字中的转义序列。

所以 "\b" 实际上是 2 个字符,\b。只有当您 echo -e 时,然后它们才会被替换。

例子:

text="a\bb\bc"
t=$(echo -e $text)
echo ${#t}
5 # the correct length

关于Bash 不应将颜色代码计为可见字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15450441/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com