Take the 2-minute tour ×

There is a file with single column of numbers:


And there is a second file with many fields. I'm trying to do a very simple thing: print 1-st column of big file for all the lines with numbers listed in first file (line 12,15 etc).

I came up with the one-liner:

awk 'FNR==NR{array[NR]=$1;next}(NR in array){print $1}' lines.txt input.txt  > output.txt

But it gives me an empty output file and I have no idea why, don't mind some help with this. I guess it's "NR in array" which doesn't work as I expect.

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

NR is the overall input line number. In the second file, NR starts out at the last line number from the first file plus one, and increases from there. The second condition will never match.

I'm guessing you are looking for something like this instead:

awk 'FNR==NR{array[$1]=1;next}
    (FNR in array){print $1}' lines.txt input.txt  > output.txt

Obviously, FNR is the line number within the current file.

Notice also that we are reading the numbers from the first file into the array, not their line numbers in the first file.

share|improve this answer
Thank you! Using NR instead of FNR was my obvious mistake. But why you use array[$1]=$1? First $1 is index, second $1 is a value. I didn't get why index is important here? Is it because in case of array[NR]=$1 index was always equal to number of rows, i.e. was a constant? –  Grigory Sharov Oct 1 '13 at 16:25
Look closer; the key is $1 and the value is the constant 1. The value is unimportant; we only really care that the keys are the numbers we want, because this is what FNR in array examines. Associative arrays are nice because you can find whether a key is present without a search. –  tripleee Oct 1 '13 at 16:30
add comment

You have to use FNR in array instead, because FNR is the line number in the current file and doesn't count all the lines which were already read in lines.txt.

share|improve this answer
add comment

Your Answer


