使用多个文件中的AWK将列添加到csv表中 [英] Adding columns to a csv table with AWK from multiple files

查看:238
本文介绍了使用多个文件中的AWK将列添加到csv表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过AWK从多个文件中获取值来构建一个csv表.我有两个文件一起工作,但是我无法扩展它.我目前正在获取第二个文件的输出,并附加第三个文件,依此类推.

I'm looking to build a csv table by getting values from several files with AWK. I have it working with two files, but I can't scale it beyond that. I'm currently taking the output of the second file, and appending the third, and so on.

以下是示例文件:

#file1  #file2  #file3  #file4
100     45      1       5
200     23      1       2
300     29      2       1
400     0       1       2
500     74      4       5

这是目标:

#data.csv
1,100,45,1,5
2,200,23,1,2
3,300,29,2,1
4,400,0,1,2
5,500,74,4,5

这是我正在工作的:

awk 'FNR==NR { a[FNR""] = NR", " $0","; next } { print a[FNR""], $0}' $file1 $file2

结果:

1, 100, 45
2, 200, 23
3, 300, 29
4, 400, 0
5, 500, 74

但是当我尝试使其在3个或更多文件上运行时,就像这样:

But when I try and get it to work on 3 or more files, like so:

awk 'FNR==NR { a[FNR""] = NR", " $0","; next } { print a[FNR""], $0; next } { print a[FNR""], $0}' $file1 $file2 $file3

我得到以下输出:

1, 100, 45
2, 200, 23
3, 300, 29
4, 400, 0
5, 500, 74
1, 100, 1 
2, 200, 1 
3, 300, 2
4, 400, 1
5, 500, 4

在第一列中,行数重新开始,在第二列中,它也重复第一个文件.在第三列中,它将第三和后续文件添加为新行,我希望这些文件应作为列添加.无需新行.

In the first column the line count restarts, and the second column it also repeats the first file. In the third column is where it adds the third and subsequent files as new rows, where I would expect these should be added as columns. No new rows required.

任何帮助将不胜感激.我已经从Stack Exchange中学到了大部分的AWK,而且我知道这里缺少一些基本知识.谢谢,

Any help would be greatly appreciated. I have learned most of my AWK from Stack Exchange, and I know I'm missing something fundamental here. Thanks,

推荐答案

已经回答的您可以使用paste.要使用逗号分隔的行号获得准确的输出,您可以这样做

as already answered you can use paste. To get the exact output with comma delimited line numbering, you can do this

paste -d, file{1..4} | nl -s, -w1

  • -s,将数字分隔符设置为逗号(默认为制表符).
  • -w1设置数字宽度,因此没有初始空格(因为默认值较大)
    • -s, sets number separator as comma (default is tab).
    • -w1 sets number width, so there are no initial spaces (because default is bigger)
    • 使用awk

      awk    '{a[FNR]=a[FNR] "," $0} 
          END {for (i=1;i<=length(a);i++) print i a[i]}' file{1..4}
      

      这篇关于使用多个文件中的AWK将列添加到csv表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆