【问题标题】:iterating matching and merging datas迭代匹配和合并数据
【发布时间】:2014-02-19 18:14:57
【问题描述】:

我有两个名为

的 csv 文件

alexa_products.csv

name,         sku,      urle,     product,  data

amazon,   amazon.com,   current,  mobile,   seller

vinnes,   vinnes.com,   current,  cellular, Aircel_Indore

数据.csv

name,          sku,      urle,    product,   data

linkedin.com, linkeidn,  current, local,     blah

airtel.com,    airtel,   current, sim,       Airtel

amazon.com,    amazon,   face, network,    buyier

vinnes.com,    vinnes,   look, hands,      ddde

现在我必须匹配 file1 中的名称和 file2 中的 sku,如果有任何匹配项,我必须只打印另一个 csv 文件中的特定列

【问题讨论】:

  • 欢迎来到 SO。通常人们来这里问一个问题。类似的东西:“这是我的问题;我尝试过 X,但我得到的不是 Y,而是 Z。我哪里出错了?” .你能改进你的帖子变成这样的问题吗?
  • 您是否特别需要perl 的回答,或者您愿意接受别人?您标记了问题perl,但没有尝试自己编写任何perl 脚本...
  • @Floris 我想要 perl 中的答案
  • @user3231692 - 你需要自己尝试解决这个问题

标签: arrays perl sorting csv hash


【解决方案1】:

当您在等待某人为您提供perl 解决方案时,这里是awk 单线:

awk 'BEGIN{FS=","}FNR==NR{if(NR>1){a[$2]=$2;next}}($2 in a){print $0}' alexa_products.csv Data.csv

解释:

BEGIN     - do this before anything else
FS=","    - set "field separator" to comma
FNR==NR   - do this if the total number of records == records in this file;
            this means you are processing the first file
if(NR>1)  - skip the first line (or you will get "sku" to match "ski")
a[$2]=$2; - create an array a with value = key = field 2 (the sku column)
($2 in a) - processing the second file : is the sku found in the array
print $0  - if so, print the whole line

【讨论】:

  • 感谢您的回复。我不想要亚马逊和葡萄藤,但我想要匹配列的整个行数据
  • 嗯,这是对“我必须只打印另一个 csv 文件中的特定列”的奇怪解释。只需将最后一个 $2 更改为 $0 即可打印整行
  • 我已经更新了问题,请查看编辑...我有数据差异...现在如果发现任何匹配项,我必须将两个文件中的数据打印到另一个文件中?...
【解决方案2】:
  1. 散列较小文件中给定列的值。
  2. 处理较大的文件,
  3. 如果给定列中的值作为键存在于哈希中,则输出它。

使用Text::CSV 处理CSV 数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    相关资源
    最近更新 更多