Cut colored text ignoring color tags

colorscutterminaltmux

My problem is similar to this one; I want to use cut to simulate a nowrap on tmux, but my output is colored. I know how many columns I want to keep (50) but I don't know how many color tags will be on the output. Cutting with cut -c-50 generates all kinds of different output, depending on how many escape characters (color tags) are on each line.

So, summing it up: can I cut the text with a fixed width ignoring the colors, so that I always end up with 50 colored characters?

Best Answer

Try:

perl -pe 's/^((?:(?>(?:\e\[.*?m)*).){50}).*/$1\e[m/'

That assumes ansi-type escape sequences.

Those are with escape sequences like \e[31m to set a colour and \e[m or \e[0m to reset it. Above, we add \e[m at the end of each line, but that might not always be desirable depending on the input.