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.
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.
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.
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.
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 listgrep -li
prints file name instead of matching pattern. I use -i
for case insensitive.