string 如何在文件中搜索多个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2584456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:41:45  来源:igfitidea点击:

How to search for multiple strings in a file

bashfilesearchstring

提问by topwoman

I want to search for the occurrence of string1 OR string2 OR string3, etc. in a file, and print only those lines (to stdout or a file, either one). How can I easily do this in bash?

我想在文件中搜索 string1 OR string2 OR string3 等的出现,并只打印那些行(到 stdout 或文件,任一)。我怎样才能在 bash 中轻松地做到这一点?

回答by ghostdog74

you can also use awk

你也可以使用 awk

awk '/string1|string2|string3/' file

With awk, you can also easily use AND logic if needed.

使用 awk,您还可以根据需要轻松使用 AND 逻辑。

awk '/string1/ && /string2/ && /string3/' file

回答by Chen Levy

grep "string1\|string2\|string3" file_to_search_in

回答by frankc

One other choice, especially if the number of strings you want to search is large, is to put those strings into a file delimited by newlines and use:

另一种选择,尤其是当您要搜索的字符串数量很大时,是将这些字符串放入由换行符分隔的文件中并使用:

grep -f file_of_strings file_to_search

回答by dawg

With Perl:

使用 Perl:

perl -lne 'print if /string1|string2|string3/;' file1 file2 *.fileext

With Bash one liner:

使用 Bash 一个衬垫:

while read line; do if [[ $line =~ string1|string2 ]]; then echo $line; fi; done < file

With Bash script:

使用 Bash 脚本:

#!/bin/bash

while read line
do
    if [[ $line =~ string1|string2|string3 ]]; then
       echo $line
    fi
done < file 

Note that the spaces around "[[ $line =~ string1|string2 ]]" are all relevant. ie these fail in Bash:

请注意,“[[ $line =~ string1|string2 ]]” 周围的空格都是相关的。即这些在 Bash 中失败:

[[ $line=~string1|string2 ]] # will be alway true...
[[$line =~ string1|string2]] # syntax error

回答by Randy Proctor

Also:

还:

grep -e 'string1' -e 'string2' -e 'string3'