Reputation: 3375
I'm using fold
to wrap my input file. I noticed that some colored lines are shorter.
I found that bash
counts color codes as characters, even if there are not visible.
Example:
$ text="\e[0;31mhello\e[0m"; echo -e "$text - lenght ${#text}"
hello - lenght 18
$ text="hello"; echo -e "$text - lenght ${#text}"
hello - lenght 5
This happens for other non visible characters also:
$ text="a\bb\bc"; echo -e "$text - lenght ${#text}"
c - lenght 7
Is it possible to change this behavior? I would like that coreutils
programs (bash
and fold
for example) could count only the visible characters.
Upvotes: 4
Views: 1727
Reputation: 4597
Its not perfect, but you can remove the format bytes with a tool like sed
before counting.
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
Upvotes: 1
Reputation: 96266
This is not a complete solution for your problem, but it's important to know that bash doesn't handle escape sequences in literals.
So "\b"
is really 2 characters, \
and b
. Only when you echo -e
, then they are substituted.
Example:
text="a\bb\bc"
t=$(echo -e $text)
echo ${#t}
5 # the correct length
Upvotes: 4