Searching for and printing two key words in set

Viewed 34

If I have a list like this:

aaa
bbb
ccc
ddd
eee
fff
ggg

Is there a command where I can specify for aaa and bbb?
I know if I want to search for aaa I can do: sed -n '/aaa/p'
But is there a way I can search for bbb at the same time as I am searching for aaa?
Something like this? sed -n '/aaa/bbb/p'

1 Answers

You can use this solution with GNU and FreeBSD sed:

s='aaa
bbb
ccc
ddd
eee
fff
ggg'
sed -nE '/aaa|bbb/p' <<< "$s"

See an online sed demo. Here, E option enables the POSIX ERE syntax and | means an alternation inside the regex pattern.

Another portable way with -e to chain sed commands:

sed -n -e '/aaa/p' -e '/bbb/p'
Related