1

I have this awk command:

awk -F, 'NR==FNR{_1[$1]++;next}_1[$1]' file1 file2

I actually almost know what the program is doing, but I don't know what _1 means. The intention is to compare two files, one has 1 field and the other has 4 fields.

Here's what I'm trying to do. I have these files, I need to know which numbers on file1 is in file 2 and then print the record of file 2.

file1

89611862
89613696
84126597
88690669
60147342

file2

84126597,12345300943529348333,2805058C30730000,28
88767631,12345712012010684248,2805058C30730002,28
83218719,12345712012012622594,2805058C30730006,28
89611862,12345712012010174449,2805058C30730014,28
85933710,12345712012007778032,2805058C3073001A,26
88690669,12345712012012060159,2805058C3073001E,28
60147342,12345712012011235922,2805058C30730030,28
89613696,12345712012008043980,2805058C3073003C,28
84783612,12345712012031117926,2805058C3073004C,28
awk -F, 'NR==FNR{arr[$1]++;next}arr[$1]' file1 file2

But it only prints the last found record:

60147342,12345712012011235922,2805058C30730030,28 

Thanks!

  • take care with the line terminators; some lines from file1 may be terminated by cr/lf, windows-mode. Do you have the same problem if you replace -F, with -F'[,\r]'? – mosvy Apr 7 at 20:00
  • You are absolutely right!! I change it and it works, and yes, I have that problem with the file1. Thanks!! – Chila Mendez Apr 7 at 20:19
2

awk does not allow digit-only variable names (and variable names can't begin with a digit as well), so _1 is a trick to prepend _ in front of 1; so, _1 is a variable name in your awk program, which happens to be an array in this case.

Here is an example:

% awk 'BEGIN {1 = 3}'
awk: cmd. line:1: BEGIN {1 = 3}
awk: cmd. line:1:          ^ syntax error

% awk 'BEGIN {_1 = 3}'  # runs fine

As an aside, you should use readable variable names in your program to have better maintainability unless you're golfing intentionally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.