Grep output to awk command

Hi Team(Solaris 5.8/Ksh),

How can we save grep output to awk variable when grep returns more than one line or word.
abc.log

[Makarand] # more abc.log
Hi Makarand
How r u
bye Makarand
Hello

when grep returns only 1 word below command works

nawk -v var=`cat abc.log |grep "Hello"` 'BEGIN { if (var != "") {print var;exit;}}'

output Hello
When grep command returns more than one word or more than one line it fails

nawk -v var=`cat abc.log |grep "Hi"` 'BEGIN { if (var != "") {print var;exit;}}'

output

nawk: can't open file BEGIN { if (var != "") {print var;exit;}}
source line number 1

or

nawk -v var=`cat abc.log |grep "Makarand"` 'BEGIN { if (var != "") {print var;exit;}}'

output:

nawk: can't open file BEGIN { if ("var" != "") {print var;exit;}}
source line number 1

how to store & compare multiline or multi word grep output in awk variable???

There is no need to use cat or grep with awk.

What are you exactly trying to accomplish?

Maybe using arrays would help you. For example to store all lines containing the word "Makarand" into an array, you can use:

awk '/Makarand/{array[$0]};END{for (x in array) print x}' abc.log

Just enclose the var in quotes:

awk -v var="`cat kk2 |grep "Makarand"`" 'BEGIN { if (var != "") {print var;exit;}}'

As @pilnet101 points , your code is getting messy. :slight_smile:

Note: I moved the double quotes...

nawk -v var="`cat abc.log |grep Hi`" 'BEGIN { if (var != "") {print var;exit;}}'

thanks mates for responses
i want to grep word Makarand if found i want to mail the grep output to my email....if doest not found .. do nothing...
I tried in below way but not working

nawk -v var="`cat abc.log |grep Makarand`" 'BEGIN { if (var != "")  {system "print var | mailx -s "Found something" abc@abcsys.com" |getline users;print users}}'

Note: 1) Grep out put can be multiline
2) I have to grep only once...

Is there any need to use awk here? Can't you just use grep and the mailx command alone?

---------- Post updated at 10:51 AM ---------- Previous update was at 10:46 AM ----------

How about something like:

var=$(grep Makarand abc.log)  
[[ ! -z "${var}" ]] && {
        echo "${var}"|mailx -s "Found something" abc@abcsys.com"|echo "${var}"|head -1        
}
1 Like

yes...working...thanks
actualy it is some other user's post which i was trying to solve...i will reply to him..anyways thanks