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

时间:2013-03-16 14:27:21

标签: bash

我正在使用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)只计算可见字符。

2 个答案:

答案 0 :(得分:3)

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

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

示例:

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

答案 1 :(得分: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