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?



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.

| improve this answer | |
  • This works to some extent but has some issues with the last escape sequence until the cut limit exceeds the string length + escape sequences. See this test run. – Thor Sep 2 '12 at 20:55
  • Good point, I've edited my answer. – Stéphane Chazelas Sep 2 '12 at 21:09
  • 1
    This is almost it; however, there's still a small problem. Consider this example. The input loses the last 'm' of the escape sequence and prints garbage in the end of the output. – Rafael Martins Sep 2 '12 at 23:24
  • Wonderful. Ran perfectly with a log file of ~30k lines, so I'm considering it done. Thanks a lot for taking the time to help me. – Rafael Martins Sep 3 '12 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.