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

您好我有两个文件如下: File1.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


但它并没有给我所有价值都在相同的id下


繁花如伊
浏览 174回答 4
4回答

慕森卡

请您尝试以下操作。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 B11 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.

MMTTMM

如果密钥在第二个文件中,您可以将该行添加到字典中。例子:from collections import defaultdictd = defaultdict(list)with open("f1.txt") as f1, open("f2.txt") as f2:    keys = set(f2.read().splitlines())    for line in f1:        k, *rest = line.split()        if k in keys:            d[k]+=rest>>> print(*d.items(),sep="\n")('10', ['A', 'B', 'C', 'A', 'D', 'K', 'A', 'K', 'B'])('11', ['X', 'Y', 'Z', 'Y', 'X', 'A'])

当年话下

你可以试试这个:with open("File1.txt") as f1, open("File2.txt") as f2:    dictf1 = {}    for i in f1.readlines():        i = i.split()        if i[0] in dictf1.keys():            dictf1[i[0]] += i[1:]        else:            dictf1[i[0]] = i[1:]    for i in f2.readlines():        if i[:-1] in dictf1.keys():            print(i[:-1], " ".join(dictf1[i.strip()]))

偶然的你

我在这里看不到 File2.txt 的相关性。因此,如果输出的间距不重要,您可以使用此 1 行命令:sort File1.txt | awk '$1!=key {if (sum) print key sum; key=$1; sum=""} {$1=""; sum=sum $0} END {print key sum}'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python