如果满足意外情况,请用文件1中的模式替换文件2中的模式

时间:2019-01-21 18:55:18

标签: linux if-statement awk sed

我有两个制表符分隔的数据文件,文件1看起来像这样:

cluster_j_72    cluster-32  cluster-32  cluster_j_72
cluster_j_75    cluster-33  cluster-33  cluster_j_73
cluster_j_8 cluster-68  cluster-68  cluster_j_8

file2看起来像:

   NODE_148        67545   97045   cluster-32
   NODE_221        1       42205   cluster-33
   NODE_168        1       24506   cluster-68

我想确认,对于给定的行,在file1的第2列和第3列中;以及1和4相同。如果是这种情况,那么我想从列2(文件1)中获取该行的值,并在文件2中找到它,并将其替换为列1(文件1)中的值。因此,文件2的新输出将如下所示(请注意,因为第1列和第4列与群集33(file1)不匹配,因此模式不会在file2中替换):

   NODE_148        67545   97045   cluster_j_72  
   NODE_221        1       42205   cluster-33  
   NODE_168        1       24506   cluster_j_8  

我已经能够正确地设置偶然性(这里我要使用file1的值打印出来替换file2中的值):

    awk '{if($2==$3 && $1==$4){print $1}}'file1

如果在查看文件2时可以让sed从文件1绘制值($ 2和$ 1),这将起作用:

     sed 's/$2(from file1)/$1(from file1)/' file2

但是我似乎无法将此sed嵌套在先前的awk语句中,也无法让sed查找与所查找文件不同的文件格式。

谢谢!

1 个答案:

答案 0 :(得分:0)

使用awk时不需要sed,因为awk可以做sed可以做的任何事情。

这可能是您要尝试做的事情:

$ cat tst.awk
BEGIN { FS=OFS="\t" }
NR==FNR {
    if ( ($1 == $4) && ($2 == $3) ) {
        map[$2] = $1
    }
    next
}
$4 in map { $4 = map[$4] }
{ print }

$ awk -f tst.awk file1 file2
NODE_148        67545   97045   cluster_j_72
NODE_221        1       42205   cluster-33
NODE_168        1       24506   cluster_j_8