Skip to content
shellhacks.dev
Text Processing

Search recursively and skip binary files

Skip binary files in a recursive grep with --binary-files=without-match, short form below. Otherwise GNU grep 3.8 prints a notice for every binary hit.

1 min read
Summarize in AI

A recursive search through a project also reads images, archives and build output, and the results fill up with lines that say a binary file matched.

Shell
mkdir demo && cd demo
printf 'needle in notes\n' > notes.txt
printf 'needle\0data' > blob.bin
grep -r needle .
echo ---
grep -rI needle .
Text
grep: ./blob.bin: binary file matches
./notes.txt:needle in notes
---
./notes.txt:needle in notes

-I is short for --binary-files=without-match, which treats a file with NUL bytes as one that holds no match. Without it, the default action is to report that the file matched and print no line from it. Both are described in the GNU grep manual, and grep treats a file as binary when it finds NUL bytes or invalid encoding in it.

A text file in a different encoding than your locale can be classed as binary, and -I then hides real matches. Run with LC_ALL=C to compare bytes, or use -a to force text. For a code tree, git grep skips untracked and ignored files as well.

Taggedgreptext
Share

More snippets

Text Processing

Count the matches per file

Count the matching lines in each file with grep -c. With several files grep prefixes each count with the name, and -h removes the prefix for one total.

1 min read
Text Processing

Count every occurrence not just lines

Count every occurrence of a word with grep -o piped to wc -l, because grep -c counts the lines that match and a line with three hits counts as one.

1 min read
Text Processing

Match whole words only

Match whole words only with grep -w. A match must sit between non-word characters, and letters, digits and the _ character all count as word characters.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.