TransWikia.com

grep returns "Binary file (standard input) matches" when trying to find a string pattern in file

Unix & Linux Asked by answerSeeker on February 19, 2021

I’m on Ubuntu and I typed cat .bash_history | grep git and it returned

Binary file (standard input) matches

My bash_history does exist and there are many lines in it that starts with git.

What caused to display this error and how can I fix it?

5 Answers

Presumably the file .bash_history starts with non-text data, hence grep is treating the file as binary. This is confirmed by the file .bash_history output:

.bash_history: data 

You can read a few bytes from start to have a conforming view:

head -c1K .bash_history 

Here I am reading first 1 KiB.

You can pipe the STDOUT to hexdump/od or similar.


As a side note, grep takes filename(s) as argument, so cat is useless here; try this:

grep git .bash_history

Correct answer by heemayl on February 19, 2021

This can be caused by null bytes in your bash history. Removing lines with null characters may resolve the issue. You can check for them using grep's Perl-regexp mode:

grep -Pa 'x00' .bash_history

This post has suggestions for non-unix systems.

Answered by Brad Nelson on February 19, 2021

Error is due to the data in the file being binary, you can use strings command to see the human readable (i.e. strings) part which you would normally search using grep

strings data | grep -i whatever

Answered by Gajraj Singh Chouhan on February 19, 2021

I had the same problem when I want to grep my .bash_history. (Little Note: I renamed my history, so that a new one was created. This new history was not treated as a binary.)

In @heemayls answer it is stated, that grep takes filenames and cat would be useless. This is not entirely true. From greps man page:

If no files are specified, or if the file “-” is given, grep searches standard input.

So you could use cat and pipe it to grep. However this solves not the problem that .bash_history is treated as a binary. The only right thing is to use grep -a (Like in the answer from @AK_) whether you grep the history directly or with cat and a pipe.


cat .bash_history | grep -a git

or

grep -a git .bash_history

Answered by SSCMuchacho on February 19, 2021

You can use grep -a 'pattern'.

from man grep page:

-a, --text
Process a binary file as if it were text; this is equivalent to the --binary-files=text option.

Answered by AK_ on February 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP