I use (GNU) fmt
to format longer texts with nice (‘optimal’) line breaks. However, if the text contains any ANSI colour escape sequences (which are never displayed, and only serve to colour the text when displaying it), fmt
considers these as normal characters, and calculates the wrong line lengths.
I’m not sure how good literal escape characters work here, so here’s a simple example using grep
to generate the ANSI sequences. Let’s start with a long string to format.
string="Here’s an example of a rather long \
string with quite a few words in the middle \
that grep chooses to colour red."
If we don’t highlight the grep
matches, everything works fine:
echo $string | grep --color=no i | fmt -w 50
But if we highlight/colour them, fmt
considers the lines containing the letter ‘i’ to be much longer than they really are, and they are shown as rather short lines when displayed in a terminal.
echo $string | grep --color=yes i | fmt -w 50
Is there a way to avoid this? For this example I could of course use fmt
before grep
, but when the search string spans several words, this doesn’t work.