How to get AWK to output 2 fields at once

John Kane jak9213 at helios.TAMU.EDU
Mon Oct 29 07:57:19 AEST 1990


In article <297 at twg.bc.ca> bill at twg.bc.ca (Bill Irwin) writes:
>I  have what initially seemed to be a simple requirement:  get the  first
>two fields from each line in file_1, and use them as a search pattern for
>GREP to extract matching lines in file_2.  [...]

>for x in `cat file_1 | awk '{ print $1 " " $2 }'`
>do
>        grep "$x" file_2
>done

>Of course, the GREP routine executed with x having the value of the first
>field  of  the  first line of file_1, then with the value of  the  second
>field  of  the first line of file_1, then the first field of  the  second
>line, .....

>Is  there a way to get AWK to output "field_1 field_2" as the value of x,
>so  that  this  can be used as the search pattern for GREP,  rather  than
>"field_1" "field_2" "field_1" "field_2"?

Yep, There is.

for x in `cat file_1 | awk '{print "\"" $1 " " $2 "\"")'`
do
	grep "$x" file_2
done

Your problem was that you were just putting out the values as:
	field_1 field_2

By putting in the "\"" you are now getting:
	"field_1 field_2"

Hopefully this is what you need.

BTW, you can also do it:

awk '{ print "grep \"" $1 " " $2 "\" file_2" }' | sh

This outputs lines like:
	grep "field_1 field_2" file_2
	etc ...

I like to do it this way instead of the other, unless I need to do something
else with the "field_1 field_2" arguments, in addition to the grep.

-- 
 John Arthur Kane, Systems Analyst, Microcomputer Support and Training
 Texas A&M University, College Station, TX 77843  (409) 845-9999

 jak9213 at helios.tamu.edu     profs: x043jk at tamvm1.tamu.edu



More information about the Comp.unix.shell mailing list