Grep 搜索一行中的两个单词

Seb*_*ian 53 grep text-processing

我一直在寻找一种方法来过滤包含“lemon”和“rice”两个词的行。我知道如何找到“柠檬”或“米饭”,但不知道如何找到这两个。它们不需要紧挨着另一个,只是同一行文本中的一个。

Flo*_*sch 67

“都在同一行”的意思是“'米饭'后跟随机字符,然后是'柠檬'或其他方式”。

在正则表达式中是rice.*lemonor lemon.*rice。您可以使用 a 组合它|

grep -E 'rice.*lemon|lemon.*rice' some_file
Run Code Online (Sandbox Code Playgroud)

如果你想使用普通的正则表达式而不是扩展的 ( -E) 你需要在 前加一个反斜杠|

grep 'rice.*lemon\|lemon.*rice' some_file
Run Code Online (Sandbox Code Playgroud)

对于快速变得有点冗长的更多单词,使用 的多次调用通常更容易grep,例如:

grep rice some_file | grep lemon | grep chicken
Run Code Online (Sandbox Code Playgroud)


Adi*_*tya 29

您可以将第一个 grep 命令的输出通过管道传输到另一个 grep 命令,这将匹配两个模式。因此,您可以执行以下操作:

grep <first_pattern> <file_name> | grep <second_pattern>
Run Code Online (Sandbox Code Playgroud)

或者,

cat <file_name> | grep <first_pattern> | grep <second_pattern>
Run Code Online (Sandbox Code Playgroud)

例子:

让我们在文件中添加一些内容:

$ echo "This line contains lemon." > test_grep.txt
$ echo "This line contains rice." >> test_grep.txt
$ echo "This line contains both lemon and rice." >> test_grep.txt
$ echo "This line doesn't contain any of them." >> test_grep.txt
$ echo "This line also contains both rice and lemon." >> test_grep.txt
Run Code Online (Sandbox Code Playgroud)

该文件包含什么:

$ cat test_grep.txt 
This line contains lemon.
This line contains rice.
This line contains both lemon and rice.
This line doesn't contain any of them.
This line also contains both rice and lemon.
Run Code Online (Sandbox Code Playgroud)

现在,让我们grep我们想要的:

$ grep rice test_grep.txt | grep lemon
This line contains both lemon and rice.
This line also contains both rice and lemon.
Run Code Online (Sandbox Code Playgroud)

我们只得到两个模式匹配的行。您可以扩展它并将输出通过管道传输到另一个 grep 命令以进行进一步的“AND”匹配。


小智 21

尽管问题要求“grep”,但我认为发布一个简单的“awk”解决方案可能会有所帮助:

awk '/lemon/ && /rice/'
Run Code Online (Sandbox Code Playgroud)

这可以很容易地用更多单词或除“and”之外的其他布尔表达式进行扩展。


αғs*_*нιη 11

以任何顺序查找匹配项的另一个想法是使用:

grep with -P (Perl-Compatibility) option and positive lookahead regex(?=(regex))

grep -P '(?=.*?lemon)(?=.*?rice)' infile
Run Code Online (Sandbox Code Playgroud)

或者您可以在下面使用:

grep -P '(?=.*?rice)(?=.*?lemon)' infile
Run Code Online (Sandbox Code Playgroud)
  • .*?意味着匹配.出现零次或多次的任何字符,*而它们是可选的,后跟模式(ricelemon)。该?让一切可选的它(指零或一切的一次匹配之前.*

(?=pattern): Positive Lookahead:正向前瞻结构是一对括号,左括号后跟一个问号和一个等号。

因此,这将返回所有线,同时包含lemonrice随机顺序。这也将避免使用|s 和 doubled greps。


外部链接: Advanced Grep Topics Positive Lookahead – GREP for Designers


小智 7

grep -e foo -e goo
Run Code Online (Sandbox Code Playgroud)

将返回 foo 或 goo 的匹配项