How can I grep for lines containing foo AND bar, foo OR bar?
mywiki.wooledge.org·15h·
Discuss: Hacker News
🔤Text Processing
Preview
Report Post

How can I grep for lines containing foo AND bar, foo OR bar? Or for files containing foo AND bar, possibly on separate lines? Or files containing foo but NOT bar?

This is really four different questions, so we’ll break this answer into parts.

foo AND bar on the same line

The easiest way to match lines that contain both foo AND bar is to use two grep commands:

1 grep foo | grep bar
2 grep foo -- "$myfile" | grep bar

It can also be done with one grep, although (as you can probably guess) this doesn’t really scale well to more than two patterns:

1 grep -E 'foo.*bar|bar.*foo'

If you prefer, you can achieve this in one sed or awk statement:

1 sed '/foo/!d; /bar/!d'
2 awk '/foo/ && /bar/'

If you need to scale the awk solution to an arbitrary numbe…

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help