简体   繁体   English

根据数组比较的结果在awk中编写新变量

[英]Code a new variable in awk based on result of array comparison

I am comparing the values in column 3 from two files, file1 and file2. 我正在比较来自文件1和文件2的第3列中的值。 When the column's value does not match across file1 and file2, code it as 0. When the column's value does match across file1 and file2, code it as 1. For example: 当列的值在file1和file2之间不匹配时,将其编码为0。当列的值在file1和file2之间进行匹配时,将其编码为1。例如:

file 1 文件1
fid1 iid1 693 900 399 fid1 iid1 693900399
fid2 iid2 589 209 485 fid2 iid2 589209485

file2 文件2
fid0 iid0 693 448 932 fid0 iid0 693448932
fid8 iid8 482 548 589 fid8 iid8 482548589

desired output 期望的输出
fid1 iid1 693 900 399 1 fid1 iid1 693900399 1
fid2 iid2 589 209 485 0 fid2 iid2 589209485 0

I can get this output in awk, using awk 'FNR==NR{a[$3]++;next}a[$3]' file1 file2 我可以使用awk 'FNR==NR{a[$3]++;next}a[$3]' file1 file2在awk中获得此输出。

output 输出
fid1 iid1 693 900 399 fid1 iid1 693900399

But, I cannot figure out how to code a new variable based on the a[$3] array comparison, instead of printing just the rows from file1 that match. 但是,我无法弄清楚如何基于a[$3]数组比较来编码新变量,而不是仅打印file1中匹配的行。

You can do: 你可以做:

$ awk 'NR==FNR{a[$3]++;next}{$(NF+1)=(($3 in a) ? 1 : 0)}1' file2 file1
fid1 iid1 693 900 399 1
fid2 iid2 589 209 485 0

Note: 注意:

  • Using $(NF+1) may not work on old broken awk. 使用$(NF + 1)可能不适用于旧的awk。
  • This does not do line for line comparison. 这不会进行行比较。 This just checks if third column of file1 is present in file2. 这只是检查file2中是否存在file1的第三列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM