我使用fold
包装我的输入文件。我注意到有些颜色的线条更短。我发现bash
将颜色代码视为字符,即使不可见。例子:
$ text="e[0;31mhelloe[0m"; echo -e "$text - lenght ${#text}"
hello - lenght 18
$ text="hello"; echo -e "$text - lenght ${#text}"
hello - lenght 5
对于其他不可见的字符也是如此:
$ text="abbbc"; echo -e "$text - lenght ${#text}"
c - lenght 7
有可能改变这种行为吗?我希望coreutils
程序(例如bash
和fold
)只能计数可见字符。
这不是您问题的完整解决方案,但重要的是要知道bash不处理文字中的转义序列。
所以"b"
实际上是两个字符,和
b
。只有当您使用echo -e
, 然后时,它们才被替换。
的例子:
text="abbbc"
t=$(echo -e $text)
echo ${#t}
5 # the correct length
这并不完美,但您可以在计数前使用sed
等工具删除格式字节。
text="e[0;31mhelloe[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