9

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?

topwoman
  • 91
  • 1
  • 1
  • 2
  • To find all of the strings inside a file, you can run grep in FOR loop: https://unix.stackexchange.com/a/462445/43233 – Noam Manos Aug 14 '18 at 06:56

6 Answers6

18

you can also use awk

awk '/string1|string2|string3/' file

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

awk '/string1/ && /string2/ && /string3/' file
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
8
grep "string1\|string2\|string3" file_to_search_in
Chen Levy
  • 15,438
  • 17
  • 74
  • 92
3

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
bschlueter
  • 3,817
  • 1
  • 30
  • 48
frankc
  • 11,290
  • 4
  • 32
  • 49
1

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 the spaces around "[[ $line =~ string1|string2 ]]" are all relevant. ie these fail in Bash:

[[ $line=~string1|string2 ]] # will be alway true...
[[$line =~ string1|string2]] # syntax error
dawg
  • 98,345
  • 23
  • 131
  • 206
0

Also:

grep -e 'string1' -e 'string2' -e 'string3'
Randy Proctor
  • 7,396
  • 3
  • 25
  • 26
  • Thanks, Randy, worked like a charm! And, meanwhile, I found one more: egrep 'string1|string2' infile – topwoman Apr 06 '10 at 11:48
-1

Way:

awk '/Mbits/||/Gbits/{print}' 100P-TCP-f1.out