/errors/grep/binary-file-matches
grep: (standard input): binary file matches
- 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
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
printf 'hello\0world\nhello again\n' > data.bin
grep -a -c hello data.bin
grep -a 'again' data.binOutput
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
| Option | Effect |
|---|---|
| -a, --text | Process binary data as if it were text and print matching lines |
| -I | Same as --binary-files=without-match: skip binary files |
| --binary-files=TYPE | binary (default), text, or without-match |
| -c | Print 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:
iconv -f UTF-16 -t UTF-8 report.txt | grep hello