How to calculate the length of a xterm control sequence

187 Views Asked by At

I am looking to format text before passing it to stdout/console. To do this properly I need to know how long a given section of text is after being printed to the console, which requires knowing how much characters will not be printed due to them being escape sequences.

On the web I have found multiple documentations for these sequence commands, but there seems to be no quick and easy way to find out where a given escape sequence command ends unless I was to parse them. Is there a trick/solution to getting the length of any escape sequence command without parsing?

How many characters is this \x1b[38;2;20;60;122m string \x1b[0m in console?
1

There are 1 best solutions below

1
Arkadiusz Drabczyk On

You can use ansifilter:

$ printf '\x1b[38;2;20;60;122mabc\x1b[0m'  | ./ansifilter --no-trailing-nl | wc -c
3