使用AWK提取和区分列

时间:2012-08-14 01:28:21

标签: awk

我需要从任意数量的文件中提取第一列,并使用空行打印缺少条目的列。有空白部分的问题。像这样:

File1:
Alfa        Something    More stuff
Charlie     Something    More stuff
Delta       Something    More stuff
Echo        Something    More stuff
Foxtrot     Something    More stuff

File2:
Alfa        Something    More stuff
Bravo       Something    More stuff
Echo        Something    More stuff
Foxtrot     Something    More stuff

File3:
Alfa        Something    More stuff
Bravo       Something    More stuff
Charlie     Something    More stuff
Delta       Something    More stuff
Echo        Something    More stuff

Output:
FileName1    FileName2    FileName3
=========    =========    =========
Alfa         Alfa         Alfa
             Bravo        Bravo
Charlie                   Charlie
Delta                     Delta
Echo         Echo         Echo
Foxtrot      Foxtrot

1 个答案:

答案 0 :(得分:1)

这是一种方法,除了一些小的格式问题:

awk '
  { 
    exists[$1] = 1;
    files[$1,ARGIND] = 1;
  }
  END {
    for (i=1; i<ARGC; ++i) {
      printf("%-20s",ARGV[i])
    }
    printf("\n");
    for (i=1; i<ARGC; ++i) {
      printf("%-20s","=================")
    }
    printf("\n");
    for (name in exists) {
      for (i=1; i<ARGC; ++i) {
        if (files[name,i]) {
          printf("%-20s",name);
        }
        else {
          printf("%-20s","");
        }
      }
      printf("\n");
    }
  }
' file1 file2 file3