【问题标题】:Substitute values based on condition and compare values from multiple files with AWK根据条件替换值并使用 AWK 比较来自多个文件的值
【发布时间】:2020-07-09 22:54:42
【问题描述】:

我花了一天的时间试图解决这个问题,但没有成功。我有两个这样的文件:

文件1:

chr id pos
14 ABC-00 123
13 AFC-00 345
5  AFG-99 988

文件2:

index id chr
1 ABC-00 14
2 AFC-00 11
3 AFG-99 7

我想检查文件 1 中 chr 的值 != 是否来自文件 2 中的 chr 是否具有相同的 ID,如果这是真的,我想打印两个文件中的一些列以得到如下所示的输出。

预期的输出文件:

ID OLD_chr(File1) NEW_chr(File2)
AFC-00 13 11
AFG-99 5 7
.....

Total number of position changes: 2

我有一个警告。在文件 1 中,我必须在比较文件之前替换 $1 列中的一些值。像这样:

30 and 32 >> X
31 >> Y
33 >> MT

因为在文件 2 中这些值是这样编码的。然后比较两个文件。我到底怎么才能做到这一点?

我尝试重新编码文件 1:

awk '{ 

        if($1=30 || $1=32) gsub(/30|32/,"X",$1);
        if($1=31) gsub(/31/,"Y",$1);
        if($1=33) gsub(/33/,"MT",$1);
  
        print $0
  
    }'  File 1 > File 1 Recoded

我试图匹配列并打印输出:

awk 'NR==FNR{a[$1]=$1;next} (a[$1] !=$3){print  $2, a[$1], $3 }' File 1 File 2  > output file

【问题讨论】:

  • 我认为您想要$1==30 而不是$1=30(其他比较也是如此)。和 ++ 用于示例数据/所需输出/当前输出和...代码!祝你好运。
  • 由于您想在脚本中包含从 30 到 X 等的转换,您应该在示例中包含其中一些案例来证明该要求,因此当我们进行测试时,我们可以验证我们的脚本是否那个。

标签: linux awk sed


【解决方案1】:
$ cat tst.awk
BEGIN {
    map[30] = map[32] = "X"
    map[31] = "Y"
    map[33] = "MT"
    print "ID", "Old_chr("ARGV[1]")", "NEW_chr("ARGV[2]")"
}
NR==FNR {
    a[$2] = ($1 in map ? map[$1] : $1)
    next
}
a[$2] != $3 {
    print $2, a[$2], $3
    cnt++
}
END {
    print "Total number of position changes: " cnt+0
}

.

$ awk -f tst.awk file1 file2
ID Old_chr(file1) NEW_chr(file2)
AFC-00 13 11
AFG-99 5 7
Total number of position changes: 2

【讨论】:

  • 我挠了挠头,直到它发现XYMT 只是要保护的编码,但在file1file2 中不存在...
  • 谢谢埃德。学习AWK还有很长的路要走。我会到达那里! :D
【解决方案2】:

像这样:

awk '
    BEGIN{                                         # executed at the BEGINning
        print "ID OLD_chr("ARGV[1]") NEW_chr("ARGV[2]")"
    }
    FNR==NR{                                       # this code block for File1
        if ($1 == 30 || $1 == 32) $1 = "X"
        if ($1 == 31)             $1 = "Y"
        if ($1 == 33)             $1 = "MT"
        a[$2]=$1
        next
    }
    {                                              # this for File2
        if (a[$2] != $3) {
            print $2, a[$2], $3
            count++
        }
    }
    END{                                           # executed at the END
        print "Total number of position changes: " count+0
    }
' File1 File2

ID OLD_chr(File1) NEW_chr(File2)
AFC-00 13 11
AFG-99 5 7
Total number of position changes: 2

【讨论】:

  • 谢谢 Gilles,非常感谢您抽出宝贵时间帮助我。
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2012-04-08
  • 2021-09-27
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 2018-05-14
相关资源
最近更新 更多