【问题标题】:awk - Merge two files by matching columns and append the columns values of second file to the lineawk - 通过匹配列合并两个文件并将第二个文件的列值附加到该行
【发布时间】:2015-02-11 08:01:30
【问题描述】:

我在 awk 中有一个不寻常的合并请求。希望你能帮忙。

文件1

pl1,prop1,20

pl1,prop2,30

pl1,prop3,40

pl2,prop1,70

pl2,prop2,80

pl2,prop3,90

pl3,prop1,120

pl3,prop2,130

pl3,prop3,140

文件2

store1,pl1

store2,pl1

store3,pl2

store4,pl3

store5,pl2

store6,pl1

输出:

prop1, store1-20, store2-20, store3-70, store4-120, store5-70, store6-20

prop2, store1-30, store2-30, store3-80, store4-130, store5-80, store6-30

prop3, store1-40, store2-40, store3-90, store4-140, store5-90, store6-40

规则

  1. file1.column1 应该匹配 file2.column2
  2. 对于所有匹配的行 - file2.column1 应与 file1.currentLine.column3 连接

非常感谢,

【问题讨论】:

  • How to merge two files using AWK? 的可能重复项(用例略有不同,但处理第二列而不是第一列并更改输出顺序听起来并不难,试一试,然后询问是否你被困在尝试:))
  • 感谢 Tensibai,会尽力让您知道
  • 我的问题和How to merge two files using AWK?很不一样。输出由 file1.column2 驱动,此值不应重复。除此之外,我仍然在使用 Awk,因此很难利用所有选项。

标签: bash awk


【解决方案1】:

我假设这些空行实际上不在您的输入文件中。

使用具有真正数组的 GNU awk:

gawk -F, '
    NR==FNR { prop[$2][$1] = $3; next } 
    { pl[$2][$1] = 1 } 
    END {
        for (key in prop) {
            printf "%s", key; 
            for (subkey in prop[key]) {
                for (store in pl[subkey]) {
                    printf ", %s-%d", store, prop[key][subkey]
                }
            }
            print ""
        }
    }
' File1 File2
prop1, store1-20, store2-20, store6-20, store3-70, store5-70, store4-120
prop2, store1-30, store2-30, store6-30, store3-80, store5-80, store4-130
prop3, store1-40, store2-40, store6-40, store3-90, store5-90, store4-140

【讨论】:

  • 谢谢格伦。但是我收到所有数组数组的语法错误。任何建议都会有所帮助
  • 返回什么:gawk --version
  • 我有 GNU Awk 3.1.5
  • 我意识到我需要 gawk 4.x 及更高版本才能使数组工作,我会尝试让你知道。谢谢格伦 - 周末愉快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多