gpt4 book ai didi

awk - 如何在 awk 中与多个文件相比获得一个文件中的唯一行

转载 作者:行者123 更新时间:2023-12-02 05:24:06 25 4
gpt4 key购买 nike

我有如下所示的制表符分隔文件,并且希望获得如下所述的输出。我在某种程度上尝试了以下命令,但无法完成最终任务。为了使问题更清楚,描述有点长。

文件1.txt

col1  col2  col3  col4  col5
ID1 str1 234 cond1 0
ID1 str2 567 cond1 0
ID1 str3 789 cond1 1
ID1 str4 123 cond1 1

文件2.txt

col1  col2  col3  col4  col5
ID2 str1 235 cond1 0
ID2 str2 567 cond2 1
ID2 str3 789 cond1 1
ID2 str4 123 cond2 0

文件3.txt

col1  col2  col3  col4  col5
ID3 str1 235 cond1 0
ID3 str2 567 cond2 1
ID3 str3 789 cond1 1

我想在 file1.txt 中找到唯一的行与其余文件相比,file2.txtfile3.txt 。专栏col2col3用作搜索的关键字。我有一个附加条件,仅当 col4="cond1" 时才删除尽管按键col2col3位于 file2.txtfile3.txt 。下面是代码和输出:

 awk -F "\t" 'NR == 1  { OFS="\t"; print $0; next }
NR == FNR { a[$2,$3] = $0; next }
{ if ($4=="cond1") delete a[$2, $3] }
END { for (i in a) print a[i] }' file1.txt file2.txt file3.txt

输出:

 col1  col2  col3  col4  col5
ID1 str1 234 cond1 0
ID1 str2 567 cond1 0
ID1 str4 123 cond1 0

现在,我想添加附加列,其中包含 col1 列表值和计数 col1不满足条件 $4=="cond1" 的文件中的值在file2.txtfile3.txt

期望的输出

 col1    col2    col3  col4    col5    col6  col7
ID1 str1 234 cond1 0 NA NA
ID1 str2 567 cond1 0 ID2,ID3 2
ID1 str4 123 cond1 0 ID2 1

尽管str2567存在于 file2.txtfile3.txt ,来自 file1.txt 的行自 col=="cond2" 起保留在file2.txtfile3.txt 。现在的问题是获取这些附加列 col6col7 。有什么想法吗?

注意:这是 file1 与 file2 和 file3 进行比较的测试用例。在实际场景中,会有更多的文件与文件进行比较。

最佳答案

awk -vOFS="\t" '!c{c=$0"\tcol6\tcol7";next}NR==FNR{a[$2$3]=$0;next}{if($4=="cond1"){delete a[$2$3]}else{b[$2$3]=b[$2$3]?b[$2$3]","$1:$1}}END{print c;for(i in a){s=split(b[i],t,",");if(!s){b[i]=s="NA"}print a[i],b[i],s}}' a b c
col1 col2 col3 col4 col5 col6 col7
ID1 str2 567 cond1 0 ID2,ID3 2
ID1 str1 234 cond1 0 NA NA
ID1 str4 123 cond1 1 ID2 1

关于awk - 如何在 awk 中与多个文件相比获得一个文件中的唯一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com