如何根据连续两行的内容 grep 目录?

Nat*_*ong 11 grep regular-expression

如何 grep包含“Foo”的行的目录,但在下一行还包含“Bar”时才获得匹配项?

Nat*_*ong 7

@warl0ck 用 指出了我正确的方向pcregrep,但我说的是“包含”,而不是“是”,我问的是目录,而不是文件。

这似乎对我有用。

pcregrep -rMi 'Foo(.*)\n(.*)Bar' .
Run Code Online (Sandbox Code Playgroud)


dai*_*isy 6

Grep 本身似乎不支持它,请改用 pcregrep:

Foo
Bar
Foo
abc
Run Code Online (Sandbox Code Playgroud)

pcregrep -M "Foo\nBar" file

得到了:

Foo
Bar
Run Code Online (Sandbox Code Playgroud)

  • OP 没有说 `Foo` 和 `Bar` 将构成整条线。 (3认同)

Gil*_*not 6

使用sed脚本:

#!/bin/sed -nf

/^Foo/{
    h         # put the matching line in the hold buffer
    n         # going to nextline
    /^Bar/{   # matching pattern in newline
        H     # add the line to the hold buffer
        x     # return the entire paragraph into the pattern space
        p     # print the pattern space
        q     # quit the script now
    }
}
Run Code Online (Sandbox Code Playgroud)

使用它:

chmod +x script.sed
printf '%s\n' * | ./script.sed
Run Code Online (Sandbox Code Playgroud)

printf这里展示的每一条线在当前目录下的所有文件,并将它传递给sed

注意:这是按字母顺序排序的。

有用pattern spacehold space 这里的更多信息。

grymoire.com有关于shell编程的好东西。