【问题标题】:Comapare the 1st Column of one file with the all column of 2nd file比较一个文件的第一列和第二个文件的所有列
【发布时间】:2020-06-10 19:24:15
【问题描述】:

我想将一个文件的第一列与第二个文件的所有列进行比较,如果找到匹配项,则打印第一列(第一个文件)和在第二个文件中找到匹配项的完整行。

示例输入文件_1

RAM_1
RAM_2
RAM_3
RAM_4
RAM_5
RAM_6

示例输入文件_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】:

    您能否尝试以下操作,仅基于所示示例,使用 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.
    

    【讨论】:

      【解决方案2】:

      这可能对你有用(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 的行,或者只打印原始行。

      【讨论】:

        【解决方案3】:

        另一种方法,假设单词边界足以避免部分匹配并且要匹配的文本没有正则表达式元字符:

        $ 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-01
          相关资源
          最近更新 更多