0

I am having some difficulty finding the number of hex characters in a file. For example:

grep -o \x02 file | wc -l
0

There should be about 3M matches here, but it doesn't seem like the \x02 character is being recognized here. For example (in python):

>>> s=open('file').read()
>>> s.count('\x02')
2932267

2 Answers2

0

This seems to do what you want on macOS:

printf "\x02\n3\n\x02" | grep -c "\x02"
2
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
0

The answer by Mark Setchell may be OK for MacOS but doesn't seem to work on debian using bash (tested with bash 4.4, grep 2.27).

I could get a match using the -P directive (for Perl regex)

user@host:~ $ printf '\x02\n3\n\x02' | grep -c -P '\x02'
2
user@host:~ $ printf '\x02\n3\n\x02' | grep -c -P '\xFF' #same input, different pattern
0
user@host:~ $ printf '\x02\n3\n\xff' | grep -c -P '\xFF' #match with unmatching case
2

Hope this helps

brunorey
  • 2,135
  • 1
  • 18
  • 26