Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to suppress a binary file matching results in grep on Linux?
The grep command in Linux is used to filter searches in files for particular patterns of characters. It displays lines that contain the pattern we are searching for, where the pattern is referred to as a regular expression.
When searching through directories containing both text and binary files, grep may attempt to process binary files, which can produce unwanted output or warnings. This article explains how to suppress binary file matching results.
Basic grep Syntax
grep [options] pattern [files]
Common grep Options
-c : Count of lines that match the pattern -h : Display matched lines only (no filenames) -i : Ignore case for matching -l : Print filenames only -n : Display matched lines with line numbers -v : Print lines that do not match the pattern -r : Search recursively through subdirectories
Searching in Multiple Files
To search for a pattern in all files within a directory:
grep -rni "func main()" *
This command searches recursively (-r), ignores case (-i), and shows line numbers (-n) for the pattern "func main()" in all files.
main.go:120:func main() {}
binary_file.exe:Binary file matches
Suppressing Binary File Results
To exclude binary files from grep results, use the -I flag (capital i):
grep -I "func main()" *
The -I flag processes binary files as if they contain no matching data, effectively ignoring them.
Complete Example
grep -InH "func main()" *
This combines:
-I− Ignore binary files-n− Show line numbers-H− Print filenames for each match
main.go:120:func main() {}
Alternative Approaches
| Flag | Description | Use Case |
|---|---|---|
-I |
Ignore binary files completely | Skip binary file processing |
--binary-files=without-match |
Treat binary files as non-matching | Explicit binary handling |
--binary-files=text |
Process binary files as text | Force text processing |
Using Long Options
grep --binary-files=without-match -rn "pattern" *
This explicitly tells grep to treat binary files as non-matching, producing cleaner output focused only on text files.
Conclusion
Use the -I flag with grep to suppress binary file matching results and focus only on text files. This approach provides cleaner output when searching through directories containing mixed file types, making it easier to locate relevant matches in readable files.
