Equivalent command to grep binary files

I have a bunch of binaries and I know that inside these binaries there are strings I want to find.

I want to do a:

grep -lir "the string I am looking for"

and get a list of all binaries inside a particular directory that contain that string but grep -lir is apparently not working with these files.

Is there a command that can do this kind of search from terminal?

Asked By: Duck

||

With GNU grep, you can use -a option to make it treats binary files as text files:

grep -ali -- string file

If your grep version does not support -a, you can use ack instead. With ack 1.x, you need to include -a option, with ack 2.x, you don’t, since when searching include non-text file by default (only ignored non-text file when you did not specify any files).

Answered By: cuonglm

The command strings will extract all ascii data from a file, if you then grep its output, you can search for your data:

strings <filename> | grep "search text"
Answered By: NZD

Your question is about find binary files that contain a pattern
(and we have already very good answers!). Complementary we may like to get the occurrences.

I often use

grep -aPo '.{0,20}pattern.{0,20}'  binfile

to get a surrounding context of 20-char.

Answered By: JJoao

bgrep if lines don’t necessarily fit into memory

I keep coming back to this random repo from time to time: https://github.com/tmbinc/bgrep Install:

curl -L 'https://github.com/tmbinc/bgrep/raw/master/bgrep.c' | gcc -O2 -x c -o $HOME/.local/bin/bgrep -

Use:

bgrep `printf %s saf | od -t x1 -An -v | tr -d 'n '` myfile.bin

Sample output:

myfile.bin: c80000003
x02abc
myfile.bin: c80000007
dabc

I have tested it on files that don’t fit into memory, and it worked just fine.

I’ve given further details at: Best way to grep a big binary file?

Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.