如果文件1中的列A =文件2中的列A,则替换为文件2中的列B.

时间:2013-06-07 11:27:56

标签: python linux awk

通常我会使用R并执行merge.by,但是这个文件似乎对于部门中的任何计算机来说都太大了! (对遗传学工作的任何人的其他信息)基本上,插补似乎删除了snp ID的rs数字,我留下了染色体:位置信息到位。所以我创建了一个包含我想要的所有rs号的链接文件,并希望用文件2中的rs号替换文件1中的Chr:Pos列。

所以我试图想出一种代码方式:

If $3 of file 1 = $5 of file 2, replace $3 file 1 with $2 of file 2.

文件1看起来像

1111 1111 1:10583  G G
1112 1112 1:10583  G G
1113 1113 1:10583  G G
1114 1114 1:10583  G G
1115 1115 1:10583  G G

文件2看起来像

1   rs58108140  0   10583       1:10583
1   rs192319073 0   105830003   1:105830003
1   rs190151039 0   10583005    1:10583005
1   rs2809302   0   105830229   1:105830229
1   rs191085550 0   105830291   1:105830291

所需的输出将是:

1111 1111 rs58108140  G G
1112 1112 rs58108140  G G
1113 1113 rs58108140  G G
1114 1114 rs58108140  G G
1115 1115 rs58108140  G G

3 个答案:

答案 0 :(得分:2)

简单awk

$ awk 'FNR==NR{a[$5]=$2;next}$3 in a{$3=a[$3]}1' file2 file1
1111 1111 rs58108140 G G
1112 1112 rs58108140 G G
1113 1113 rs58108140 G G
1114 1114 rs58108140 G G
1115 1115 rs58108140 G G

答案 1 :(得分:0)

从file2

创建字典
with open('file2', 'r') as file2:
   replacement = {}
   for line in file2:
       splited_line = line.split()
       replacement[splited_line[4]] = splited_line[1]

with open('file1', 'r') as file1:
    with open('file1_new', 'w') as file1_new:
        for line in file1:
            splitted_line = line.split()
            splitted_line[2] = replacement.get(splitted_line[1], splitted_line[1])
            file1_new.write(' '.join(splitted_line)+'\n')

答案 2 :(得分:0)

joinawk可以做到这一点。您也可以使用cut代替awk,但之后必须以其他方式对字段进行重新排序。

join -1 3 -2 5 file1 file2 | awk '{print $2, $3, $7, $4, $5}'

警告:正如sudo_O所提到的,只有文件被排序时才会起作用 - 我假设它们是基于给定的例子。如果他们不是,这不会很快。如果它们已经排序,则不需要将它们读入内存,因为两个命令只会在读取数据时处理它们。