【问题标题】:Grep returning regex results in recursive searchGrep 返回正则表达式导致递归搜索
【发布时间】:2014-01-02 01:43:28
【问题描述】:

我已经构建了一个 grep 命令,用于在文件目录中递归搜索其中的模式。问题是 grep 只返回模式所在的文件名,而不是模式的完全匹配。如何返回实际结果?

例子:

文件somefile.bin 包含somestring0987654321�123�45� 与一百万个其他文件的目录

命令:

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

当前结果:

Binary file somefile.bin matches

想要的结果(或接近):

Binary file somefile.bin matches

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

【问题讨论】:

    标签: regex bash grep


    【解决方案1】:

    您可以尝试-a 选项:

    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.
    

    但问题是在二进制文件中没有行,所以我不确定您希望输出是什么样的。您会看到随机垃圾,可能是整个文件,可能会打印一些与您的终端混淆的特殊字符。

    如果您想将输出限制为匹配本身,请考虑使用-o 选项:

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

    上下文控制仅限于在匹配之前或之后添加一定数量的,这在这里可能无法正常工作。因此,如果您想要特定字节数的上下文,则必须更改模式本身。

    【讨论】:

    • 是的——问题是它是垃圾。当我使用十六进制编辑器搜索文件时,我发现字符串没有任何问题。所以我想问题变成了我如何以合理的方式从二进制文件中挑选字符串?
    • @CocoaPuffs 所以你只想要匹配?然后查看-o 选项。
    • 非常感谢 - 将 -o 选项与 -a 一起使用会更好,我可以使用它。 :)
    【解决方案2】:

    试试……

    grep -rnw "<regex>" <folder>
    

    容易得多。更多示例在这里 --> https://computingbro.com/2020/05/10/word-search-in-linux-unix-filesystem/

    【讨论】:

    • “试试”?它(不)在您的机器上工作吗?参数应该做什么?
    猜你喜欢
    • 2015-05-30
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多