Search code examples
bashmacosgrepfind

Recursively find hexadecimal bytes in binary files


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.


Solution

  • 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