Skip to content

/errors/grep/binary-file-matches

grep: (standard input): binary file matches

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · grep (GNU grep) 3.0updated
tool
grep
exit code
0
versions
GNU grep 3.x
os
linux, macos, windows

GNU grep prints binary file matches instead of the matching lines when it decides the input is binary: the data contains a NUL byte, or bytes that are not valid in the current locale's encoding. The match was found (exit status 0), but grep hides the line to avoid dumping binary data to the terminal. Add -a (--text) to see the lines.

The wording depends on the version. GNU grep 3.5 and later print grep: (standard input): binary file matches (or grep: FILE: binary file matches) on standard error; older versions, such as the grep 3.0 shipped with Git for Windows, print Binary file (standard input) matches on standard output.

Reproduce it

bash
printf 'hello\0world\nhello again\n' > data.bin
cat data.bin | grep hello
echo "exit status: $?"

Output

Binary file (standard input) matches
exit status: 0

Fix: force text mode with -a

bash
printf 'hello\0world\nhello again\n' > data.bin
grep -a -c hello data.bin
grep -a 'again' data.bin

Output

2
hello again

-a treats the file as text. Lines that contain NUL bytes are printed raw, so pipe them through cat -v if the terminal output looks garbled.

Other options

OptionEffect
-a, --textProcess binary data as if it were text and print matching lines
-ISame as --binary-files=without-match: skip binary files
--binary-files=TYPEbinary (default), text, or without-match
-cPrint only the number of matching lines (works for binary input too)
LC_ALL=C grep ...Treat every byte as a character, so invalid UTF-8 no longer counts as binary

UTF-16 files

Files saved as UTF-16 (for example Out-File output in Windows PowerShell 5.1) contain a NUL byte after every ASCII character. grep sees them as binary, and even -a will not match hello, because the bytes are h, NUL, e, NUL and so on. Convert first:

bash
iconv -f UTF-16 -t UTF-8 report.txt | grep hello

Sources