1

I'm using grep within bash shell to find a series of hexadecimal bytes in files:

$ find . -type f -exec grep -ri "\x5B\x27\x21\x3D\xE9" {} \;

The search works fine, although I know there's a limitation for matches when not using the -a option where results only return:

Binary file ./file_with_bytes matches

I would like to get the offset of the matching result, is this possible? I'm open to using another similar tool I'm just not sure what it would be.

Jack O'Leary
  • 235
  • 3
  • 11

2 Answers2

3

There is actually an option in grep that is available to use

-b --byte-offset  Print the 0-based byte offset within the input file

A simple example using this option:

$ grep -obarUP "\x01\x02\x03" /bin

prints out both the filename and byte offset of the matched pattern inside a directory

/bin/bash:772067:
/bin/bash:772099:
/bin/bash:772133:
/bin/bash:772608:
/bin/date:56160:

notice that find is actually not needed since the option -r has already taken care of the recursive file searching

etopylight
  • 1,239
  • 1
  • 10
  • 15
  • I cannot confirm `-obaUP` works correctly. `hexdump` displays different data at the found offset. – midenok Jul 28 '22 at 23:02
1

Not at a computer, but use:

od -x yourFile

or

xxd yourFile

to get it dumped in hex with offsets on the left side.

Sometimes your search string may not be found because the characters do not appear contiguously but are split across two lines. You can pass the file through twice though, with the first 4 bytes chopped off the second time to make sure your string is found intact on one pass or the other. Then add the offest back on and sort and uniq the offsets.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432