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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With