3

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程序(bash例如fold)只能计算可见字符。

4

2 回答 2

4

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

所以"\b"实际上是 2 个字符,\并且b. 只有当你echo -e然后他们被替换。

例子:

text="a\bb\bc"
t=$(echo -e $text)
echo ${#t}
5  # the correct length
于 2013-03-16T14:45:11.830 回答
0

它并不完美,但您可以使用sed计数之前的工具删除格式字节。

text="\e[0;31mhello\e[0m";
echo -e "# $text - lenght ${#text}";
# hello - lenght 18
x=$(echo -e "$text" | sed "s/$(echo -e "\e")[^m]*m//g");
echo "# $x - ${#x}"
# hello - 5
于 2019-05-16T14:24:15.470 回答