4

I've checked out a lot of links on how to grep individual escape characters or literal strings, but I just cannot get them to combine to find the background-red ANSI escape sequence ^[41m, even typing the ^[ as both Ctrl+V+Ctrl+[ and the two literal characters ^+[ and using both the -E and -F flags.

The raw bytes I am trying to find, given by hexdump are:

1b 5b 33 37 6d 1b 5b 34 31 6d 30 2e 30 30 25

Where this corresponds to WHITE FOREGROUND RED BACKGROUND 0.00%. I'm producing these codes with Python's colorama package and Fore.WHITE+Back.RED, just in case anyone is curious.

So, what is the secret I am missing?

  • What is the problem of \grep '\^\[41m' ? – 林果皞 Nov 21 '16 at 7:41
  • Doesn't work for me with GNU grep 2.16. – Ken Y-N Nov 21 '16 at 7:45
  • Can you attach the part of ^[41m content of the target file ? Use hexdump -C <filename>. I have no problem to grep it with GNU grep 2.16. – 林果皞 Nov 21 '16 at 8:42
5

but I just cannot get them to combine to find the background-red ANSI escape sequence ^[41m

If you use vim to open this file, you will know it's not ^[41m, instead it's ^[[41m, which ^[ navigate by arrow key as a set:

enter image description here

1b is Escape represent by single escape character ^[ which can be invoked by Ctrl+V follow by Esc. ^[ look like 2 characters but it's not, it's single:

xb@dnxb:~/Downloads/grep$ ascii 1b
ASCII 1/11 is decimal 027, hex 1b, octal 033, bits 00011011: called ^[, ESC
Official name: Escape

xb@dnxb:~/Downloads/grep$

Do this (Use Ctrl+V follow by Esc to create ^[, then continuously type \[41m):

xb@dnxb:~/Downloads/grep$ hexdump -C /tmp/2
00000000  1b 5b 33 37 6d 1b 5b 34  31 6d 30 2e 30 30 25 0a  |.[37m.[41m0.00%.|
00000010
xb@dnxb:~/Downloads/grep$ \grep '^[\[41m' /tmp/2
0.00%
xb@dnxb:~/Downloads/grep$ \grep '^[\[41m' /tmp/2 | hexdump -C
00000000  1b 5b 33 37 6d 1b 5b 34  31 6d 30 2e 30 30 25 0a  |.[37m.[41m0.00%.|
00000010
xb@dnxb:~/Downloads/grep$ 

Ensure you escape grep by prefix \ to avoid its alias --color affect:

enter image description here

[Alternative]:

  1. \grep -P '\e\[41m' (Credit: OP's comment)
  2. \grep '^[\[41m' , which use Ctrl+V follow by Ctrl+[ to create ^[. Useful when backspace in my keyboard is not 0x08, but i can use Ctrl+V follow by Ctrl+H (^H get from ascii 08) to produce it.
  • 2
    Thank you for that - I see the problem was mostly me not realising there was both a [ from the ^[ and the literal [. Since my initial post, I'd also discovered that \grep -P "\e\[41m" is an alternative. – Ken Y-N Nov 21 '16 at 23:54
  • 1
    \grep $'^\x1b\[41m' will work without perl regex or inserting a literal escape sequence, so it is editor friendly and works on mac. – Andy Aug 28 '19 at 14:16

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.