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

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.


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

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

Tags:

Binary

Grep

Files