3

is there any way to grep 2 strings in ksh and only return true if both the string found?

we can use the egrep command if any of the string is found. but for matching all the string and return true only all the string present.

grep "string1" "sring2" file.txt is not working.

Kindly help. Thanks in advance.

Edit:

Please note that if grep is not used what other option we can use for this purpose. Also the first string is present in 1st line of the file and the string2 is present in some other line of the file.

Pravej Khan
  • 142
  • 2
  • 10

4 Answers4

3

You can try

grep "string1.*string2" file

In this test string1 must come before string2 in same line to bee true.


Or you can do:

grep string1 file | grep string2 

This will be true if string1 and string2 is found


Using awk

awk '/string1/ && /string2/' file

To search on any line

awk '/string1/ {f1=1} /string2/ {f2=1} END {if (f2 && f1) print "found"}' file

To get exit status (cred Adrian)

awk '/string1/ {f1=1} /string2/ {f2=1} END {exit !(f1 && f2)}' file

This will give exit status 0 of both pattern is found, 1 if not

Jotne
  • 40,548
  • 12
  • 51
  • 55
1
$ echo "foo bar quux" | awk 'BEGIN{r=1} /foo/&&/bar/{r=0} END{exit r}'
$ echo $?
0

$ echo "foo bar quux" | awk 'BEGIN{r=1} /blah/&&/blubb/{r=0} END{exit r}'
$ echo $?
1

For a more dynamic approach check out Dennis Williamson's answer here.

Community
  • 1
  • 1
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
1

If you want both patterns to be present in the same or in different line (in the same file) consider this simple thing:

grep string1 file.txt && grep string2 file.txt

It will be successful only if both (&&) were successful, it will optimize the Boolean logic and only run second if the first was successful - which does not matter, unless you want to do something more:

You can group it and make an 'then/else' kind of thing - mind the () which give you the result of the whole grep && grep: (grep string1 file.txt && grep string2 file.txt) && echo "This file is OK" || echo "I don't like this file"

lukaszku
  • 11
  • 1
0

Try to use the following:

grep 'word1\|word2\|word3' /path/to/file

Or maybe on UNIX:

grep -e pattern1 -e pattern2 /path/to/file