Results 1 to 9 of 9
Hello,
Is there a way using /bin/grep that I print lines that contains BOTH String1 and String2?
Thanks....
- 03-19-2009 #1Just Joined!
- Join Date
- Mar 2009
- Posts
- 9
grep question
Hello,
Is there a way using /bin/grep that I print lines that contains BOTH String1 and String2?
Thanks.
- 03-19-2009 #2Linux Guru
- Join Date
- Nov 2007
- Posts
- 1,695
Code:grep <STRING1> filename | grep <STRING2>
- 03-19-2009 #3Just Joined!
- Join Date
- Mar 2009
- Posts
- 9
Thanks. I was dabbling with Regular expressions
... I guess my next question is how do I match a line which contains EITHER String1 or String2
Thanks again.
- 03-19-2009 #4Linux Guru
- Join Date
- Nov 2007
- Posts
- 1,695
C'mon man...
Just run two commands...
Code:grep <STRING2> filename
Code:grep <STRING1> filename
- 03-19-2009 #5Linux Newbie
- Join Date
- Mar 2009
- Posts
- 228
Or you can use one command:
Code:grep -e 'string1' -e 'string2' filename
- 03-19-2009 #6Linux Guru
- Join Date
- Nov 2007
- Posts
- 1,695
Absolutely true, but the "no brainer" way to me would be to run two commands - no thought required.
Maybe there is some weird "one command" requirement. But if so, it would be helpful if that was included in the OP's question.
Does this count?
Code:grep <STRING1> filename; grep <STRING2> filename
- 03-19-2009 #7Linux Newbie
- Join Date
- Mar 2009
- Posts
- 228
- 03-20-2009 #8
This will pipe only lines which contain string1 to grep, which will try to find lines that containe string2, but will not find any because the first grep command only found string1.
Your other example specifies the filename, which doesn't account for using STDIN, but isn't really what the OP wanted.Code:sagacious@amd:~$ cat ./testfile string1 string2 sagacious@amd:~$ grep string1 ./testfile | grep string2 sagacious@amd:~$
The OP wanted grep to match lines that contained string1 and string2 in the same execution. I suppose that's obvious now, but I guess I felt it necessary to correct your first example.
I personally use the regex pattern that lomcevak posted.
- 03-20-2009 #9Linux Guru
- Join Date
- Nov 2007
- Posts
- 1,695
Please check your sample file again. You have string1 and string2 in TWO lines.

Of course you will not find string1 and string2 in the same line using your test. Try making a valid test file (or use the messages log) and you will see it works fine.
No, that is *your* assumption and OP never made any such requirement.The OP wanted grep to match lines that contained string1 and string2 in the same execution.


Reply With Quote
