Cocoa Puffs
Cocoa Puffs

Reputation: 774

Grep returning regex results in recursive search

I've constructed a grep command that I use to search recursively through a directory of files for a pattern within them. The problem is that grep only returns back the file names the pattern is in, not the exact match of the pattern. How do I return the actual result?

Example:

File somefile.bin contains somestring0987654321�123�45� in a directory with one million other files

Command:

$ grep -EsniR -A 1 -B 1 '([a-zA-Z0-9]+)\x00([0-9]+)\x00([0-9]+)\x00' *

Current result:

Binary file somefile.bin matches

The desired result (or close to it):

Binary file somefile.bin matches

<line above match>
somestring0987654321�123�45�
<line below match>

Upvotes: 1

Views: 1014

Answers (2)

A-ARon
A-ARon

Reputation: 1

Try...

grep -rnw "<regex>" <folder>

Much easier. More examples here --> https://computingbro.com/2020/05/10/word-search-in-linux-unix-filesystem/

Upvotes: 0

Lev Levitsky
Lev Levitsky

Reputation: 65811

You can try the -a option:

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

   --binary-files=TYPE
          If the first few bytes of a file indicate that the file contains
          binary  data, assume that the file is of type TYPE.  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.  If TYPE is text, grep processes a binary file as if  it
          were  text;  this is equivalent to the -a option.  Warning: grep
          --binary-files=text might output binary garbage, which can  have
          nasty  side  effects  if  the  output  is  a terminal and if the
          terminal driver interprets some of it as commands.

But the problem is that in binary files there are no lines, so I'm not sure what you'd want the output to look like. You'll see random garbage, maybe the whole file, some special characters messing with your terminal may be printed.

If you want to restrict the output to the match itself, consider the -o option:

   -o, --only-matching
          Print  only  the  matched  (non-empty) parts of a matching line,
          with each such part on a separate output line.

The context control is limited to adding a certain number of lines before or after the match, which will probably not work well here. So if you want a context of certain number of bytes, you'll have to change the pattern itself.

Upvotes: 1

Related Questions