匹配列一个单独的文件,并将匹配结果追加到文件中。

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

我想用awk将两个文件合并为一列过滤的文件,然后我想将文件2中的相关列追加到文件1中。然后我想做的是将file2中的相关列追加到file1中。

用虚拟的例子来解释更容易。

文件1

name   fruit   animal
bob    apple   dog
jim    orange  cat
gary   mango   snake
daisy  peach   mouse

文件2:

 animal number  shape
 cat    eight   square
 dog    nine    circle
 mouse  eleven  sphere

希望的输出。

 name   fruit   animal  shape   
 bob    apple   dog     circle
 jim    orange  cat     square
 gary   mango   snake   NA
 daisy  peach   mouse   sphere

第1步:需要对文件1中的第3列和文件2中的第1列进行过滤。

awk -F'\t' 'NR==FNR{c[$3]++;next};c[$1] > 0' file1 file2

这样我就有了输出。

cat    eight   square
dog    nine    circle
mouse eleven   sphere

但我不能简单地从上面的输出中剪下第三列(形状),然后把它追加到文件1中,因为文件2中没有 "蛇 "的条目。我需要能够将输出的第3列追加到文件1中,在匹配成功的地方,以及没有匹配成功的地方填上'NA'。文件1中的所有行都必须保留,所以我不能省略它们。这就是我被卡住的地方

我希望得到任何帮助,请......E

awk
1个回答
4
投票

你能不能试试下面的例子,根据GNU中的例子编写和测试。awk.

awk '
BEGIN{
  OFS="\t"
}
FNR==NR{
  a[$1]=$NF
  next
}
{
  print $0,($3 in a?a[$3]:"NA")
}'  Input_file2   Input_file1

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

awk '                               ##Starting awk program from here.
BEGIN{                              ##Starting BEGIN section from here.
  OFS="\t"                          ##Setting TAB as output field separator here.
}
FNR==NR{                            ##Checking condition FNR==NR which will be TRUE when first Input_file file2 is being read.
  a[$1]=$NF                         ##Creating array a with index $1 and value is $NF for current line.
  next                              ##next will skip all further statements from here.
}
{
  print $0,($3 in a?a[$3]:"NA")     ##Printing current line and checking if 3rd field is present in array a then print its value OR print NA.
}'  file2  file1                    ##Mentioning Input_file names here.
© www.soinside.com 2019 - 2024. All rights reserved.