如何使用Perl在CSV文件中合并多行 [英] How to merge multiple lines in a csv file using Perl

查看:184
本文介绍了如何使用Perl在CSV文件中合并多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我编写将合并csv文件行的代码.我的csv文件如下所示,

Please help me in writing a code which will merge the lines of a csv file. My csv file is as shown below,


output.csv

abc,1,2,3,4,5
abc,3,5,60,3
abc,4,5,6
def,2,5,6,7
def,3,4,5,6

这只是一个例子.我的csv文件数据每次都在不断变化.因此,它不仅限于abc(3行)或def(2行). 请帮助我放置代码,以便我的csv文件显示如下:

This is just an example. my csv file data keeps on changing each time. So, it is not limited to abc ( 3 rows) or def( 2 rows). Please help me to put the code so my csv file displays as shown below:


output.csv

abc,1,2,3,4,5,3,5,60,3,4,5,6
def,2,5,6,7,3,4,5,6

我尝试使用Text :: CSV读取csv并尝试使用哈希.但是,当我尝试将数组转换为哈希时,我陷入了困境.我在这里有点困惑.请帮帮我.

I tried reading csv using Text::CSV and tried hash. But I got stuck up when I tried to convert array to hash. I'm little confused here.Please help me out.

推荐答案

假定第一个字段不包含逗号:

Assuming the first field doesn't contain commas:

perl -nle '
    ($key,$vals) = /^([^,]+),(.*)/;
    push @{$final_lines{$key}},$vals;
    END{
        for $key (sort keys %final_lines){
            print join ",",$key,@{$final_lines{$key}}
        }
    }
' < input_file > output_file

这篇关于如何使用Perl在CSV文件中合并多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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