Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide ANSI colour escape codes from fmt

Tags:

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.

like image 305
Karl Ove Hufthammer Avatar asked Jul 12 '09 21:07

Karl Ove Hufthammer


1 Answers

There doesn't seem to be a good way to resolve that using grep and fmt. I recommend you run fmt first and then use sed instead of grep for searching. For example:

echo The search string will be highlighted red. | fmt -w 50 | sed ":a;$!N;$!ba;s/search[ \n]string/\x1b\[1;31m&\x1b\[0m/g"
like image 153
Coding With Style Avatar answered Oct 12 '22 07:10

Coding With Style