How to Combine Two Search Words with "Grep" (And)

How to combine two search words with grep (AND)

To see the files containing both words (possibly on different lines), use -l and xargs:

grep -il "hello" *.html | xargs grep -il "peter"

Edit

If your files have spaces in their names, then we need to be a little more careful. For that we can use special options to grep and xargs:

grep -ilZ "hello" *.html | xargs -0 grep -il "peter"

How to grep for two words existing on the same line?

Why do you pass -c? That will just show the number of matches. Similarly, there is no reason to use -r. I suggest you read man grep.

To grep for 2 words existing on the same line, simply do:

grep "word1" FILE | grep "word2"

grep "word1" FILE will print all lines that have word1 in them from FILE, and then grep "word2" will print the lines that have word2 in them. Hence, if you combine these using a pipe, it will show lines containing both word1 and word2.

If you just want a count of how many lines had the 2 words on the same line, do:

grep "word1" FILE | grep -c "word2"

Also, to address your question why does it get stuck : in grep -c "word1", you did not specify a file. Therefore, grep expects input from stdin, which is why it seems to hang. You can press Ctrl+D to send an EOF (end-of-file) so that it quits.

Match two strings in one line with grep

You can use

grep 'string1' filename | grep 'string2'

Or

grep 'string1.*string2\|string2.*string1' filename

Merge the output of two greps into one file

You can easily combine both commands in a row, like:

grep 'substring1' file1.txt > outfile.txt ; grep 'substring2' file2.txt >> outfile.txt

The ";" separate both commands, the second command will be executed after the first has finished.

The ">>" means you append the output to the already existing file. (if the file does not exists, there will be no difference to ">")

You can use this simple pattern for many different tasks.

Use grep to find the words that have two 's' separated by a space

grep "s s"
grep "s.*s"
grep -E "^[^s]*s[^s]*s[^s]*$"

Grep Search all files in directory for string1 AND string2

grep -r db-connect.php . | grep version


Related Topics



Leave a reply



Submit