Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 6 down vote accepted

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.

share|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
1  
Thanks. Another edit again. –  Stéphane Chazelas Sep 3 '12 at 6:41
    
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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