Linux – How to search by multiple keywords when using awk or grep

findgreplinux

I have a collection of files. I want to search through them all with grep to find all and only those which contain anywhere within them both the strings keyword1 and keyword2.

I would also like to know how to do this with awk.

Best Answer

For grep, the pipe symbol separates strings in a combination regexp; on some systems, it may be necessary to use egrep to activate this functionality:

[madhatta@anni ~]$ egrep 'exact|obsol' /etc/yum.conf
exactarch=1
obsoletes=1

I would expect the syntax to be similar for awk.

Edit: yup:

[madhatta@anni ~]$ awk '/exact|obsol/ {print $1}' /etc/yum.conf
exactarch=1
obsoletes=1

Edit 2:

You have clarified your request, so here's how to do it with grep:

grep -l keyword1 * | xargs -d '\n' grep -l keyword2

This will search all the files in a given directory (*) for keyword1, passing the list of matching files onto the second grep, which will search for the second string, via xargs. I'm afraid I won't be bothering to do this with awk as it's beginning to sound a bit like a homework problem. If you have a business case for using awk, let us know.