1.

Solve : Perl: split data by line and column in csv file?

Answer»

Hi,

i have data in csv file. i want to split it base on line and COLUMN.

my code so far:

Code: [Select]CODE

#!/usr/bin/perl use strict;
use strict;
use warnings;
use TEXT::CSV_XS;

# Store our CSV file name
my $file = 'input.csv';

open( CSV_XS, '<', $file )
or die( 'Unable to open csv file ', $file, "\n" );

open MYFILE, ">output.csv";
select MYFILE;

my $csv = new Text::CSV_XS;
foreach my $line (<CSV_XS>) {
if ( $csv->parse($line) ) {

my @data = $csv->fields();
print $data[0], ',share,', $data[1], ',emotions,', $data[2],
',broadcast,', $data[3], ',social,', $data[4], ',other,', $data[5],
',feedback,', $data[6], ',funding,', $data[7], ',recruit,', $data[8],
',promotion,', $data[9], "\n";
}
else {
print 'Unable to parse CSV line: ', $line, "\n";
}
}
close(CSV_XS);
-----data---
WorkerId,share,emotions,broadcast,social,other,feedback,funding,recruit,promotion
A1LWAFOQEFVU9K,20119,20116,,20111|20112|20113|20115|20117|20120,|||||||20118|Not in English||,,,,20114
A3ACYKMVJAEAIZ,20105,20104|20106,,20102|20104|20108|20109|20110,|||||||||,20101,,,20103|20105|20107|20110


----Current output-----
A1LWAFOQEFVU9K,share,20119,emotions,20116,broadcast,,social,20111|20112|20113|20115|20117|20120,other,|||||||20118|Not in English||,feedback,,funding,,recruit,,promotion,20114
A3ACYKMVJAEAIZ,share,20105,emotions,20104|20106,broadcast,,social,20102|20104|20108|20109|20110,other,|||||||||,feedback,20101,funding,,recruit,,promotion,20103|20105|20107|20110


what i need is:
A1LWAFOQEFVU9K share 20119
A3ACYKMVJAEAIZ share 20105
A3ACYKMVJAEAIZ emotions 20104
A3ACYKMVJAEAIZ emotions 20106
A1LWAFOQEFVU9K emotions 20116
A1LWAFOQEFVU9K broadcast ## this empty, i would LIKE remove it.
A3ACYKMVJAEAIZ broadcast ## this empty, i would like remove it.
A1LWAFOQEFVU9K social 20111
A1LWAFOQEFVU9K social 20112
A1LWAFOQEFVU9K social 20113
A1LWAFOQEFVU9K social 20115
A1LWAFOQEFVU9K social 20117
A3ACYKMVJAEAIZ social 20102
A3ACYKMVJAEAIZ social 20104
A3ACYKMVJAEAIZ social 20108
A3ACYKMVJAEAIZ social 20109
A3ACYKMVJAEAIZ social 20110
.........


Any help is much appriciated. Thank you.

_____________________

No spam, thanks.
-- kpac

I don't know how to do this via a programming approach, so what I would do is IMPORT the data in to Microsoft Excel, which can parse, or split, the data into columns. If you don't have Excel, then the free OpenOffice is an option, and I believe you could use either the spreadsheet (Calc) or the database (simple called Base) component of OpenOffice.



Discussion

No Comment Found