I have a binary file and I need to count occurrences of certain string in this file or even list then with offsets. In Windows or Linux- for this task I use Fedora 12 and Windows 2000.
3 Answers
On Linux with GNU grep:
grep -F --text -o --byte-offset mystring binaryfile
Example:
$ grep -F --text -o --byte-offset option /bin/tar
226542:option
237529:option
237612:option
...
Explanation of the parameters:
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines,
any of which is to be matched. (-F is specified by POSIX.)
-a, --text
Process a binary file as if it were text; this is equivalent to the
--binary-files=text option.
-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with
each such part on a separate output line.
-b, --byte-offset
Print the 0-based byte offset within the input file before each line
of output. If -o (--only-matching) is specified, print the offset of
the matching part itself
To count the occurrences add | wc -l
to the command line.
-
Is it possible to get count only? I know I asked for offsets, but for the count too.– IvanHMay 15, 2012 at 19:01
-
1
-
Agent Ransack - Free File Searching Utility
Immediate results Found text is shown with highlighted keywords so you don't need to waste time opening each file looking for the
right information.Boolean expressions Combine search terms using the familiar Boolean operators AND, OR, NOT.
- Office formats Support for popular Office formats including Office 2007 and OpenOffice.
- Perl regex Support for Perl compatible regular expressions.
- 64-bit Version Natively compiled 64-bit version for improved compatibility.
- Fast searching Highly efficient search algorithms mean that you spend less time waiting for results.
- Printing and Exporting Results can be shared with others through printing and exporting.
-
-
Yes, it can handle binary values. See the screenshot, it has also found
dll
files.– userMay 16, 2012 at 6:42
In Linux, you can use strings -a [filename] | grep [string] | wc -l
In Windows, you can use the strings * | findstr /i [string]
, with the strings utility from Sysinternals.
-
How are multiple occurrences on the same line counted, as one or more? May 16, 2012 at 13:49
-
Your answer says there are 39 occurrences of "option" in /bin/tar (
strings -a /bin/tar | grep option | wc -l
), while mine says 45 (grep -F --text -o --byte-offset option /bin/tar | wc -l
). Dec 16, 2020 at 12:05
strings -a filename | grep string | wc -l
.