1

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.

0

3 Answers 3

2

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.

4
  • What I want is not OR, but AND Commented Oct 10, 2011 at 10:04
  • That's an ambiguous question. Do you want a list of files that contain both keywords anywhere, or a list of files that contain both keywords on the same line, or all lines that contain both keywords from a single file? Commented Oct 10, 2011 at 12:00
  • It's the first case. Commented Oct 11, 2011 at 4:50
  • See Edit 2 above; also, I have edited your question to clarify your request. Commented Oct 12, 2011 at 8:01
1

Search in one file

Using grep to find lines with either "keyword1" or "keyword2" in the file "myfile.conf":

grep -e "keyword1\|keyword2" myfile.conf 

The escaping of the pipe | character with a backslash is at least required in zsh.

Search in all files in a directory

To search for files containing either "keyword1" or "keyword2" in a directory:

grep -r -e "keyword1\|keyword2" /path/to/my/directory 

If you want to do a case-insensitive search, add the -i option as well.

0

If I understand correctly, you want to search all the files which contains keyword1 and keyword2 in a specific folder, so, try this:

$ find /path/to/folder -type f -print0 | xargs -0 grep -li "keyword1" | \ xargs -I '{}' grep -li "keyword2" '{}' 
  • -print0 | xargs -0 take cares of file names with blank spaces
  • -I tells xargs to replace '{}' with the argument list
  • grep -li prints file name instead of matching pattern. I use -i for case insensitive.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.