将一个文件的第1列与第2个文件的所有列进行比较。

问题描述 投票:0回答:1

我想比较一个文件的第1列和第2个文件的所有列,如果发现匹配,则打印第1列(第1个文件)和在第2个文件中发现匹配的完整行。

例子 输入file_1

RAM_1
RAM_2
RAM_3
RAM_4
RAM_5
RAM_6

例子 输入file_2

RAM_7 RAM_3
RAM_8 RAM_10 RAM_15 RAM_2
RAM_6 RAM_16 RAM_4
RAM_11 RAM_5 RAM_18 RAM_20 RAM_19
RAM_1 RAM_8 RAM_9 RAM_12

预期产出

RAM_1  RAM_1 RAM_8 RAM_9 RAM_12
RAM_2  RAM_8 RAM_10 RAM_15 RAM_2
RAM_3  RAM_7 RAM_3
RAM_4  RAM_6 RAM_16 RAM_4
RAM_5  RAM_11 RAM_5 RAM_18 RAM_20 RAM_19
RAM_6  RAM_6 RAM_16 RAM_4

我已经尝试固定列数,但它只打印文件的第一行。

 awk 'NR==FNR{a[$1]=$0} $1 in a && $2 in a && $3 in a{print a[$1] ORS a[$2] ORS a[$3]}' file_2 file_1
awk sed
1个回答
2
投票

请你尝试以下的方法,仅基于所示的示例,用GNU编写 awk.

awk '
FNR==NR{
  a[$0]=$0
  next
}
{
  for(i=1;i<=NF;i++){
    if($i in a){
      print a[$i],$0 | "sort -k1"
    }
  }
}' file1  file2

解释。 为上述内容添加详细解释。

awk '                                  ##Starting awk program from here.
FNR==NR{                               ##Checking condition FNR==NR which will be TRUE when Input_file1 is being read.
  a[$0]=$0                             ##Creating an array named a with index current line and its value is current line.
  next                                 ##next will skip all further statements from here.
}
{
  for(i=1;i<=NF;i++){                  ##Going through all fields here in current line.
    if($i in a){                       ##checking condition if current field is inside array then do following.
      print a[$i],$0 | "sort -k1"      ##Printing value of array a with index of current field then current line printing here and sorting it by first field.
    }
  }
}' file1  file2                        ##Mentioning Input_file names here.

1
投票

这可能对你有用(GNU sed)。

sed -E '1{x;s/^/cat file2/e;x};G;s/^(\S+)(\n.*)*\n([^\n]*\<\1\>[^\n]*).*/\1 \3/;P;d' file1

在开头的 file1 拷贝 file2 到保持空间。

对于每一行的 file1,附录 file2 并使用模式匹配和回溯引用,或者生成包含第一列的行从 file1 及其对应的线从 file2 或者直接打印原始行。


0
投票

另一种方法,假设词的边界足以避免部分匹配,并且要匹配的文本没有regex元字符。

$ awk 'NR==FNR{a[$0]; next} {for(k in a) if(k ~ "\\<"$1"\\>") print $0, k}' f2 f1
RAM_1 RAM_1 RAM_8 RAM_9 RAM_12
RAM_2 RAM_8 RAM_10 RAM_15 RAM_2
RAM_3 RAM_7 RAM_3
RAM_4 RAM_6 RAM_16 RAM_4
RAM_5 RAM_11 RAM_5 RAM_18 RAM_20 RAM_19
RAM_6 RAM_6 RAM_16 RAM_4
© www.soinside.com 2019 - 2024. All rights reserved.