【问题标题】:Split a CSV file using AWK, while reading from a different file for naming the output files使用 AWK 拆分 CSV 文件,同时从不同的文件中读取以命名输出文件
【发布时间】:2014-02-01 02:24:40
【问题描述】:

我有一个 CSV 文件,如下所示:

group1, item1
group1, item2
group2, item3
group1, item4
.....

我已设法按组将此文件拆分为单独的 csv 文件(group1.csv.dat、group2.csv.dat 等)。每个文件都包含属于特定组的所有项目。

group1.csv.dat:

item1, true
item2, true
item4, true
.....

group2.csv.dat:

item3, true
.....

我使用过以下 AWK:

awk -F, '{print $2",true" > $1".csv.dat"}' file1

现在,我有第二个文件(比如说文件 2),如下:

group1, GRFS+NC, 4
group2, GRTU+NC, 6 
....

如何使用 AWK 读取此文件,以便将第一步中创建的文件命名为 GRFS4.csv.dat、GRTU6.csv.dat 而不是 group1.csv.dat、group2.csv.dat?优选地,我想将处理合并到第一步中。非常感谢...

【问题讨论】:

    标签: shell csv awk


    【解决方案1】:
    awk -F, '{split($2,a,"+");print $2",true" > a[1]""$3".csv.dat"}' file2
    

    【讨论】:

    • 请注意,文件名中会出现尾随空格。
    • 感谢您的回答。这将仅根据来自 file2 的信息生成文件。我想做的基本上是在我的问题中重命名由 AWK 生成的文件(例如,获取 group1.csv.dat,在 file2 中查找“group1”并通过连接将 group1.csv.dat 重命名为 GRFS4.csv.dat相关领域)。
    • 正如之前多次讨论过的,输出重定向右侧的无括号串联会产生未定义的行为。你需要在它周围加上括号。此外,a[1]$3 之间的空字符串 ("") 完全没有任何作用。
    【解决方案2】:

    你需要这样的东西,未经测试:

    awk '
    NR==FNR{ name[$1] = $3 $6 ".csv.dat"; next }
    { print $2 ",true" > name[$1] }
    ' FS='[, +]' file2 FS=',' file1
    

    只需计算 file2 中的字段,以确保 $3 和 $6 是正确的字段。添加一个调试 for 循环以将它们全部打印出来,看看您是否不确定。

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 2017-06-29
      相关资源
      最近更新 更多