How to handle color codes when trying to use grep, sed, etc.

I am trying to use sed to handle some output from a command that generates colored lines (this is git diff, but I don't think it matters). I am trying to match the “+” sign at the beginning of the line, but this mixes up with the color code that precedes the “+”. Is there an easy way to deal with this problem or do I need to use some kind of complex regular expression to match the color code.

If possible, I would like to keep the line coloring.

+6
linux unix bash grep sed
source share
3 answers

If you have to have coloring, you have to do something ugly:

$ git diff --color web-app/db/schema.rb |grep '^^[\[32m+ 

This ^[ is actually a raw escape character ( Ctrl + V ESC in bash, ASCII 27). You can use cat -v to determine the required escape sequences:

 $ git diff --color web-app/db/schema.rb |cat -v ^[[1mdiff --git a/web-app/db/schema.rb b/web-app/db/schema.rb^[[m ^[[1mindex 45451a2..411f6e1 100644^[[m ^[[1m--- a/web-app/db/schema.rb^[[m ^[[1m+++ b/web-app/db/schema.rb^[[m ... 

Such things will work fine with versions of GNU sed , awk , ... YMMV with versions other than GNU.

An easier way is to rotate the coloring:

 $ git diff --no-color file 

But you can trade nice results for slightly ugly regular expressions.

+3
source share

There is really no need to deal with ugly regular expressions. You can simply pass the config variable to the git command that you use to maintain color.

 git -c color.diff=always diff | cat 

This also works for git status

 git -c color.status=always status -sb | cat 
+2
source share

That ugly expression should do it

git diff --color src/Strmrs.h| grep $'^\(\x1b\[[0-9]\{1,2\}m\)\{0,1\}+'

  • $'...' will make the \ x1b character an ESC character (aka ^[ ) - this can probably be avoided, I was too lazy to read manpage
  • the color sequence (ESC, left bracket, 1-2 digits and the letter m ) is enclosed in an external set of \(\) , which then become optional with \{0,1\} , the only optional element is last + .
  • It is assumed that at the beginning of the line no more than one color sequence
+1
source share

All Articles