gpt4 book ai didi

python - 如果 id 匹配,比较两个文件并水平打印所有值?

转载 作者:行者123 更新时间:2023-12-04 21:14:00 25 4
gpt4 key购买 nike

嗨,我有两个文件如下:
文件1.txt

10   A   B  C
10 A D K
11 X Y Z
10 A K B
11 Y X A

文件2.txt
10
11
12

预期的输出是
10 A  B  C  A  D  K  A  K  B
11 X Y Z Y X A

我试过命令 grep -f File1.txt file2.txt
但它并没有给我所有值(value)都在相同的id下

最佳答案

请您尝试以下操作。

awk '
FNR==NR{
val=$1
$1=""
sub(/^ +/,"")
a[val]=(a[val]?a[val] OFS:"")$0
next
}
($1 in a){
print $1,a[$1]
}
' File1.txt File2.txt

输出如下:
10 A B C A D K A K B
11 X Y Z Y X A

解释:为上述代码添加详细说明。
awk '                                ##Starting awk program from here.
FNR==NR{ ##Checking condition if FNR==NR which will be true for first file1.
val=$1 ##Creating variable val with $1 value of it.
$1="" ##Nullify $1 here.
sub(/^ +/,"") ##Substituting initial space with NULL for current line.
a[val]=(a[val]?a[val] OFS:"")$0 ##Creating array a with index val and keep concatenating its value to it.
next ##next will skip further statements from here.
}
($1 in a){ ##Checking condition if $1 of current line comes in array a then do following.
print $1,a[$1] ##Printing $1 of current line and value of array a with $1 value.
}
' File1.txt File2.txt ##Mentioning Input_file names here.

关于python - 如果 id 匹配,比较两个文件并水平打印所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60183053/

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