variable assignment using awk

Guys,

Could you please help me out. I need two values in two variables using awk from the o/p of grep.

example:-

grep sdosanjh <filename>
sdosanjh myhostname myfilename

NOW WHAT I WANT IS :-
sdosanjh should be in variable (say NAME)
myhostname should be in variable (say HOSTNAME)

3rd coloumn i am not bothered about.

Can you please suggest if we can do this by pipe the output of grep to awk ? :confused:

I tried the following but not able to get the value of val1 using echo.

grep sdosanjh <filename> | awk '{val=$1}{val1=$2}{print val, val1}'

Because my next line will be making a ssh connection with the myhostname
i.e. ssh $val1 [Something like that]

yes you can use awk...

NAME=`awk '/sdosanjh/{print $1}' filename`
HOSTNAME=`awk '/sdosanjh/{print $2}' filename`
set `grep sdosanjh filename`
echo $1 $2 $3

You need to provide test for failure otherwise you will get some gibberish.
these are called positional parameters and there are 9 of them. To have more you need to use shift command.
There is no need to use awk here.
Another interesting construct for long file is:

cat filename | grep sdosanjh |
while read var1 var2 var3
do
echo $var1 $var2 $var3
done

If you have less variables than items, all remainder of the read line gets packed into var3

thnaks gch... your solution looks good and working fine...

That construct is very powerful, and permits also to rearrange order of strings in a file.
You could do:

....
do
echo $var3 $var2 $var1 >> newfile
done
....

Gch,

Good solution. A bit modification :

grep sdosanjh filename |
while read var1 var2 var3
do
echo $var1 $var2 $var3
done

This is how it should be done in this particular case. Mine just illustrates, for less experienced, the fact that you can chain several commands before that while.

if you wanna go that way no need of while loop..

grep sdosanjh filename |read var1 var2 var3
echo $var1 $var2 $var3

There is a problem with this construct. Theoretically this should work all the time, but it does not. When I use Solaris sh, in some releases this works and in some it does not. This is why I did not recommend it. I guess QC at Sun is not what it used to be. I wonder which other OS this is not working. This is also warning for people moving scripts around. At the same time in ksh it works fine in the same OS. Around Solaris 6 or 7 this forced me to rewrite half of my scripts.