Nat*_*ong 11 grep regular-expression
如何 grep包含“Foo”的行的目录,但仅在下一行还包含“Bar”时才获得匹配项?
@warl0ck 用 指出了我正确的方向pcregrep
,但我说的是“包含”,而不是“是”,我问的是目录,而不是文件。
这似乎对我有用。
pcregrep -rMi 'Foo(.*)\n(.*)Bar' .
Run Code Online (Sandbox Code Playgroud)
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)
使用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 space
和hold space
这里的更多信息。
grymoire.com有关于shell
编程的好东西。
归档时间: |
|
查看次数: |
2129 次 |
最近记录: |