基于相同的第一列

时间:2015-09-01 20:48:49

标签: shell

我有以下文件:

 ABC 1234 2333 BCD
 ABC  121  123 BCD
 ABC  124  231 BCD
 ABC 2342 2344 CDK
 MBN  231   252  RFC
 MBN  230   212  RFC
 MBN  213   215  RFC
 MBN  233   235  RFC
 MBN  12   67  RTC
 MBN  67   98  TCF

我想找到基于另一个文件搜索的唯一第一和第四列值的最后一行,我的其他文件将有

  ABC 
  MBN

代码将起作用,它将在上面的文件中首先查找ABC,然后查找最后一次出现的BCD,依此类推,输出将是:

  ABC  124  231 BCD
  ABC 2342 2344 CDK  
  MBN  233   235  RFC 
  MBN  67   98  TCF

我已经开始首先发现ABC的发生为

grep ABC abovefile.txt | head -1 

1 个答案:

答案 0 :(得分:2)

您可以使用此awk命令:

awk 'NR==FNR{search[$1];next} $1 in search{key=$1 SEP $4; if (!(key in data)) c[++n]=key;
   data[key]=$0} END{for (i=1; i<=n; i++) print data[c[i]]}' file2 file1

<强>输出:

ABC  124  231 BCD
ABC 2342 2344 CDK
MBN  233   235  RFC
MBN  12   67  RTC
MBN  67   98  TCF

此解决方案使用3个阵列:

  • search来保存file2
  • 中的搜索项
  • data保存file1的记录,密钥为$1,$4
  • c用于保持已处理密钥的顺序

代码分手:

NR==FNR           # Execute next block for the 1st file in the list (i.e. file2)
{search[$1];next} # store first column in search array and move to next record
$1 in search      # for next file in the list if first col exists in search array
key=$1 SEP $4     # make key variable as $1, $4
if(!(key in data))# if key is not in data array
c[++n]=key        # store in array c with an incrementing index
data[key]=$0}     # not store full record in data array with index=key
END               # run this block at the end