Split a line on every 16th comma

99封情书 提交于 2019-12-12 01:36:23

问题


I am using perl to extract "Yes," or "No," from a large CSV, and output to a file using this code

open my $fin, "leads.csv";
my $str;
for (<$fin>) {                
  if (/^\s*\d+\.\s*(\w+)/) {  
    $str .= $1 . ",";         
  }
}
open (MYFILE, '>>data.txt');
 print MYFILE $str;
 close (MYFILE);

This is working correctly, and outputting data like this http://pastebin.com/r7Lwwz8p, however I need to break to a new line after the 16th element so it looks like this on output: http://pastebin.com/xC8Lyk5R Any tips/tricks greatly appreciated!


回答1:


The following splits a line by commas, and then regroups them by 16 elements:

use strict;
use warnings;

while (my $line = <DATA>) {
    chomp $line;

    my @fields = split ',', $line;

    while (my @data = splice @fields, 0, 16) {
        print join(',', @data), "\n";
    }
}

__DATA__
LineA,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,LineB,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,LineC,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,LineD,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,LineE,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,LineF,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,LineG,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,LineH,2,3,4,5,6,7,8,9,10,11,12

Outputs:

LineA,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
LineB,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
LineC,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
LineD,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
LineE,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
LineF,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
LineG,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
LineH,2,3,4,5,6,7,8,9,10,11,12



回答2:


Use a variable to count the number of yes/no matches that you find, and then use the mod (%) operator to insert a newline into the string.

#!/usr/bin/perl

use strict;
use warnings;

open my $fin, "leads.csv";
my $str;
my $count = 0;                
for (<$fin>) {
   if (/^\s*\d+\.\s*(\w+)/) {
     $str .= $1 . ",";
     $count++;         
   }
   $str .= "\n" unless ($count % 16);
}
open (MYFILE, '>>data.txt');
print MYFILE $str;
close (MYFILE);


来源:https://stackoverflow.com/questions/23145978/split-a-line-on-every-16th-comma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!