Is there a Linux command-line tool (like grep
) that can take a binary file and a series of bytes and return the first index where these bytes appear in the file?
2 Answers
From Fr0sT's answer to duplicate question Binary grep on Linux? - Stack Overflow:
grep --only-matching --byte-offset --max-count=1 --text --perl-regexp "\xefa" <path to file>
Note: Optional --max-count
can be used to restrict the maximum number of occurrences to search for (here we look for 1, the first).
Outputs decimal offset (starting with 0) along with found text.
In our example the Perl Regular Expression \xefa
searches for the byte with hexadecimal code ef
(the latin small letter i with diaeresis, Unicode code-point U+00EF) followed by character a
:
22157929:ïa
So, first occurrence was found at offset 22157929.
You can use xxd
to create a hexdump of the binary file like:
xxd image.jpg
Outputs (truncated to first line):
00000000: ffd8 ffe0 0010 4a46 4946 0001 0101 012c ......JFIF.....,
Then search that, e.g. with grep
like:
xxd image.jpg | grep --max-count=1 '4a' # should find the first `J`
In that output (highlighting the found occurrence), you can count the byte-columns and add to row offset (7 bytes + offset 0) to get the desired index (7).
00000000: ffd8 ffe0 0010 4a46 4946 0001 0101 012c ......JFIF.....,
It is at offset 7.
-
Not exactly what I was looking for, but the comment by @Dan Fego did the job :-) Commented Jan 6, 2012 at 23:45