Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress binary file matching results in grep [closed]

Tags:

linux

grep

When using grep in linux, the result often contains a lot of "binary file XXX matches", which I do not care about. How to suppress this part of the results, or how to exclude binary files in grep?

like image 969
RandyTek Avatar asked Sep 15 '14 17:09

RandyTek


People also ask

How do I exclude a binary file from a grep search?

To force GNU grep to output lines even from files that appear to be binary, use the -a or ' --binary-files=text ' option. To eliminate the “Binary file matches” messages, use the -I or ' --binary-files=without-match ' option, or the -s or --no-messages option.

Can grep match binary files?

By default, TYPE is binary, and grep normally outputs either a one-line message saying that a binary file matches, or no message if there is no match. If TYPE is without-match, grep assumes that a binary file does not match; this is equivalent to the -I option.

Why does grep think my text file is binary?

As this answer notes, there are two cases where grep thinks your file is binary: if there's an encoding error detected, or if it detects some NUL bytes. Both of these sound at least conceptually simple, but it turns out that grep tries to be clever about detecting NULs.

How do you grep a binary file in Unix?

You can also use the “grep –a” command combined with the “cat” command as shown below. Let's use the alternative “—binary-files=text” of the “-a” option for the grep command on the 'new.sh' binary file. It shows the same output as we got for the “-a” option.


2 Answers

There are three options, that you can use. -I is to exclude binary files in grep. Other are for line numbers and file names.

grep -I -n -H 


-I -- process a binary file as if it did not contain matching data; 
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match

So this might be a way to run grep:

grep -InH your-word *
like image 137
2 revs, 2 users 96%user184968 Avatar answered Sep 25 '22 17:09

2 revs, 2 users 96%user184968


This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$
like image 36
amadain Avatar answered Sep 23 '22 17:09

amadain