Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

grep sed awk match only regexp1 AND regexp2 AND regexp3 ..

Status
Not open for further replies.

FedoEx

Technical User
Oct 7, 2008
49
US
I know how to do OR in awk
Code:
awk '/regexp1|regexp2|regexp3/{print}' filename
or sed
Code:
sed -n '/regexp1\|regexp2/\|regexp3/p' filename
and grep
Code:
grep "regex1\|regexp2" filename
mathes lines regex1 or regex2 or regexp3
How do I match lines containing only regexp1 AND regexp2 AND regexp3
Thanks.
 

Here is one example with awk:

Code:
$ awk '/book/ && /worm/ {print}' /usr/share/dict/words
book-worm
bookworm
bookworms
 
I've found partial solution for grep
Code:
$grep "page.*versions"  /usr/share/doc/bash/README 
$files are formatted manual pages.  The `.txt' versions are
---------------
$grep "versions*.page"  /usr/share/doc/bash/README    
$
will match only lines that contain regexp1 regexp2 in the order specified.
 
grep 'versions' /usr/share/doc/bash/README | grep 'page'

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
There's got to be a way with logical AND.

 
I see. I will use awk or piped greps.
 
You can still use grep with any order of the combined REs, but if you have more than two REs, that becomes a bit cumbersome...

[tt]grep -E "page.*versions|versions.*page" /usr/share/doc/bash/README[/tt]

Of course you could script a wrapper around grep to construct the combined RE string but still... I'd prefer awk for this problem.


HTH,

p5wizard
 
[tt]egrep[/tt]" can do ORs.
Code:
egrep 'regex1|regex2|regex3' filename
 
Very doable with sed, but messy as a one-liner

E.g.

Code:
sed -n -e '/regexp1/{' -e '/regexp2/{' -e '/regexp3/p' -e '}' -e '}' filename

or

Code:
$ sed -n '
/regexp1/{
/regexp2/{
/regexp3/p
}
> }' filename

Cheers,
ND [smile]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top