AWK NR lookup with variable gives extra output

119 views Asked by At

I have two files. One has a variable as field 1. I am using this to look up a value in another file which has the variable as a record, followed by another record containing the information I want. ie I am looking up 1 to find A or 3 to find C.

1
A
2
B
3
C

I should be able to get this easily with awk using the following line.

awk '{if ($1=="3") A=NR}{ if (NR==(A+1)) print $0}' FILEIN

output should be

C

instead I am getting an output with the first line, then the correct value. ie

1
C

If I just put in the NR value rather than assigning a variable it gives me only the data I want. If I put (A+2) it gives me line 2 and the line I want, so on and so on. Any ideas as to why this is happening

1

There are 1 answers

3
Kent On BEST ANSWER

as shelter commented, at beginning the A wasn't assigned by a value, awk will take 0, so 0+1, 0+2... you see why you got the unexpected line.

you don't have to play with NR for your needs, if I understood your requirement right.

try this line:

awk '$1=="3"{getline;print;exit}' file

test with your example:

kent$  echo "1
A
2
B
3
C"|awk '$1=="3"{getline;print;exit}'
C

If you just want to fix the problem in your code, you add a &&A, like:

awk '{if ($1=="3") A=NR}{ if (NR==(A+1)&&A) print $0}'

and your line could be shorten as:

awk '$1=="3"{A=NR}NR==(A+1)&&A'