38

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?

Kusalananda
  • 333,661
Duck
  • 4,674

4 Answers4

44

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"
NZD
  • 1,422
36

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).

cuonglm
  • 153,898
  • Am I misreading ack's self-description? (in the manual) "ack 2.x will search through every regular, non-binary file that is not explicitly ignored [by blah blah]" So it sounds like ack 2.x should still stop reading a file early if the contents look binary. – Peter Cordes Jul 24 '15 at 04:09
  • 1
    @PeterCordes: That's occured when no files were selected. Try ack grep /bin/grep and you will get the result. I updated my answer to prevent confusing. – cuonglm Jul 24 '15 at 04:15
  • 1
    Try using the strings command to get the strings from your binary. – Uwe Burger Jul 24 '15 at 21:10
16

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.

JJoao
  • 12,170
  • 1
  • 23
  • 45
0

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?

Ciro Santilli OurBigBook.com
  • 18,092
  • 4
  • 117
  • 102