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?
Thanks, Chen, for your speedy reply. Of course, that works - slick!
topwoman
2010-04-06 11:54:47
Perhaps you could accept his answer also, if it works.
Anders
2010-04-06 12:06:05
Thanks, Randy, worked like a charm!And, meanwhile, I found one more:egrep 'string1|string2' infile
topwoman
2010-04-06 11:48:54
+2
A:
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
2010-04-06 12:04:35
+1
A:
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
drewk
2010-04-06 12:09:55
The curly braces can be omitted from your Bash one liner. The `do` and `done` do that for you.
Dennis Williamson
2010-04-06 13:18:55
+1
A:
There are many acceptable answers already, but 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
frankc
2010-04-06 14:53:24