迭代匹配和合并数据

时间:2014-01-28 12:37:42

标签: arrays perl sorting csv hash

我有两个名为

的csv文件

alexa_products.csv

name,         sku,      urle,     product,  data

amazon,   amazon.com,   current,  mobile,   seller

vinnes,   vinnes.com,   current,  cellular, Aircel_Indore

Data.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文件中的特定列

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

  1. 从较小的文件中散列给定列的值。
  2. 处理较大的文件
  3. 如果给定列中的值作为哈希中的键存在,则输出它。
  4. 使用Text::CSV处理CSV数据。