How to search multiple lines in a file

I want to find string string1 OR string2 OR string3 etc. in the file and print only those lines (in stdout or the file, any of them). How can I easily do this in bash?

+4
source share
5 answers

you can also use awk

awk '/string1|string2|string3/' file 

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

 awk '/string1/ && /string2/ && /string3/' file 
+10
source
 grep "string1\|string2\|string3" file_to_search_in 
+7
source

Another choice, especially if the number of lines you want to find is large, is to put these lines in a file limited by newline characters and use:

 grep -f file_of_strings file_to_search 
+2
source

With Perl:

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

With Bash, one liner:

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

With Bash script:

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

Note that all spaces around "[[$ line = ~ string1 | string2]]" matter. those. they do not work in bash:

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

also:

 grep -e 'string1' -e 'string2' -e 'string3' 
0
source

Source: https://habr.com/ru/post/1306116/


All Articles