views:

309

answers:

1

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.

+1  A: 
Coding With Style
Thanks. That’s the solution I ended up using.My real-world use of this actually involves `sed` instead of `grep`. Basically, I convert tags (such as `|` in `this is an |example| string`) to ANSI colour sequences to colour the words they span. Using `fmt` before the replacing isn’t optimal, since the tags do take up some space, which affects the word wrapping, but it’s not too bad unless a line contains very many such tags, and it’s better than running `fmt` after replacing (as the ANSI escape sequences take up many more characters).
Karl Ove Hufthammer