Need help with simple comparison in AWK

Hi,

I'm new to AWK and I'm having problems comparing a field to a string variable.

/ARTIST/ {x = $2}
$1 ~ x {print $0}

My code tries to find a record with the string "ARTIST". Once it finds it, it stores the second field of the record into a variable. I don't know what the problem is for the second line. The point is if the first field of a record matches the variable, it will print the entire record. But for some reason, it's not working.

Thanks, need help urgently!!

Can you post sample data and desired output?

There are two input files.

The first one contains data about artists.

Peter trumpet
Bob piano
John drums

The second one contains a list of commands.

ARTIST John

For example, I want to go through the second file, so I'll store "John" into variable x. Then I want to compare x to the first fields of the first file. If it equals, then I'll print out the entire record. I'm having trouble making that comparison for the variable and the field.

awk 'NR==FNR{x=$2}NR!=FNR&&$1==x' file2 file1

Hi Bart,

This is not giving desired out put. This is outputing only one value. if I put 2 entry in file2

ARTIST John
PLAYER Bob

Then it is giving output as Bob piano. it should give

Peter trumpet
Bob piano

I tried modified code like but not able to do correctly.

awk 'NR==FNR{x=$2}NR!=FNR&&$1 in x { print x[j]} ' f3 f2

Can some one make this correct?

Idea is to take values in array then compare

Thanks
Krsnadasa

Try:

awk 'NR==FNR{x[$2]=1}NR!=FNR&&$1 in x' file2 file1

Thanks Bart,

Can you please help me to understand the array concept here? As I am always confuse.

Here first we are first reading f2 and filling arr X like :

x[John]=1,x[Bob]=1 ...

is this is an associative array?

When we read file 1 then N==FNR is false then we are matching the pattern $1 from file1 in array..

 
awk 'NR==FNR{x[$2]=1}NR!=FNR&&$1 in x' file2 file1

Want to understand how array is formed and then serached.

Thanks
Krsnadasa

Yes, "x" is an associative array, with "John" and "Bob" as its keys. $1 in x is true when 1st field of file1 is among the keys of array "x" (so this is how it is being searched).