Logical AND operation with egrep

Hi All,

I need to perform logical AND operation using UNIX command.
string(space separated) is coming through web. And i dont want to create
files for that. i want to use only source file.

Any help would be appreciated.

Regards,
Sam

file1=
Joe, Linda, Bob, Terry
Kim, Rhonda, Steve, Joy

cat file1 | grep "Joe" | grep "Linda"

would output that first line of
Joe, Linda, Bob, Terry

Or, are you asking something different? Sometimes easier to understand with examples.

ok here is the example :-

below is the string coming from web application

string="str1 str2 str3"

i want to search a record/records which contain all three string by using source file only. Dont want to create any new file.

important :- string coming through web is space separated.

Or is there something else not immediately clear?

cat file | egrep "str1 str2 str3"

to find all records that have those three entries.

strings are coming through web application in a variable.

cat file|egrep "str1 str2 str3" not working.:mad:

cat test | egrep "string1 string2 string3"
string1 string2 string3

cat test
string1 string2 string3

That works, I think you need to provide more information.

sorry i forgot to mention one thing my file is CSV file,
and that command is not working with CSV file.

Its not like 'grep' will not work with csv file. It will work with all kind of text file, even with binary files.

But in case of CSV you might be having a separator, so don't forget to include separator in the pattern match.

If the colon is separator then,

egrep str1:str2:str3

If you want to find ALL combinations of str1 str2 str3 in a line from a CSV file, there is no easy regex solution. Either you pipe successive egrep's like in the joeyg's example or you can use awk.

To find all lines containing Joe and Linda in any order:

$ cat > test.file
Joe,Linda,Bobby,Terry
Kim,Rhonda,Steve,Joe
Linda,Joe,Bob,Terry

$ awk -F"," '{flag=0;for (i=1;i<=NF;i++) if($i ~ /Joe|Linda/) flag++} flag==2 {print}' test.file
Joe,Linda,Bobby,Terry
Linda,Joe,Bob,Terry

Now, imagine we are after lines with Bob and Joe, the above awk snippet will logically return:

$ awk -F"," '{flag=0;for (i=1;i<=NF;i++) if($i ~ /Joe|Bob/) flag++} flag==2 {print}' test.file
Joe,Linda,Bobby,Terry
Linda,Joe,Bob,Terry

As awk use POSIX regex we can use the ^ and $ metacharacters:

$ awk -F"," '{flag=0;for (i=1;i<=NF;i++) if($i ~ /^(Joe|Bob)$/) flag++} flag==2 {print}' test.file
Linda,Joe,Bob,Terry

What about this?

awk '/str1/ && /str2/ && /str3/' file

[EMBARASSED]
Well, it's so much... better! And so obvious.
[/EMBARASSED]

My string is coming through web application in a variable
like
VARIABLE="str1 str2 str3"

i need to use this variable in search.

This is not working when i am using my variable

awk '/$VARIABLE/' file :mad:

perhaps this ...

awk -v n=$variable '/n/' file

not working error coming

$awk -v n=$key '/n/' file.csv
awk: Cannot find or open file /n/.
The source line number is 1.