LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to grep two strings in one line in a file? (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-grep-two-strings-in-one-line-in-a-file-755265/)

thomas2004ch 09-15-2009 01:03 AM

How to grep two strings in one line in a file?
 
I want to grep in a file to find out which line contains the following two strings:

"Mon Sep 14" and "myWeb".

How can I do that?

I try using grep "Mon Sep 14 && myWeb" but it doesn't do what I want.

lutusp 09-15-2009 01:32 AM

Quote:

Originally Posted by thomas2004ch (Post 3683141)
I want to grep in a file to find out which line contains the following two strings:

"Mon Sep 14" and "myWeb".

How can I do that?

I try using grep "Mon Sep 14 && myWeb" but it doesn't do what I want.

Do you want to test whether both of two test strings are present at once, or whether either string is present?

Either A or B:

Code:

$ cat datafile | grep -P "\b(first|second)\b"
Both A and B:

Code:

$ cat datafile | grep -P "\bfirst\b" | grep -P "\bsecond\b"
The above examples will print the lines in which their specified targets appear. Remember these tests are line-oriented -- for other kinds of partitions, the test must be arranged differently.

chrism01 09-15-2009 01:55 AM

note that grep takes a filename as an arg, so cat is unneeded
Code:

grep -P "\b(first|second)\b" datafile
grep -P "\bfirst\b" datafile | grep -P "\bsecond\b"


thomas2004ch 09-15-2009 03:54 AM

Just a concrete example:

I want to grep the lines which contains string "Aug 27" and "meth='POST' file='/mycom/Calculator'" in a file called "myconfig.conf". How can I do that?

lutusp 09-15-2009 04:42 AM

Quote:

Originally Posted by thomas2004ch (Post 3683313)
Just a concrete example:

I want to grep the lines which contains string "Aug 27" and "meth='POST' file='/mycom/Calculator'" in a file called "myconfig.conf". How can I do that?

Like this:

Code:

cat myconfig.conf | grep -P "Aug 27" | grep -P "meth='POST' file='/mycom/Calculator'"

lutusp 09-15-2009 04:49 AM

Quote:

Originally Posted by chrism01 (Post 3683193)
note that grep takes a filename as an arg, so cat is unneeded
Code:

grep -P "\b(first|second)\b" datafile
grep -P "\bfirst\b" datafile | grep -P "\bsecond\b"


I'm sure you can imagine why I use "cat" in a case where there may be more than one "grep" call present on a line. This is, after all, a newbie discussion group, where aesthetics and clarity of expression matter at least as much as issues of efficiency.

To decide how much clarity of expression matters to newbies, one need only read the interminable threads about the syntax of "xargs", many of which expire more from exhaustion than resolution.


All times are GMT -5. The time now is 02:07 AM.