每隔16个逗号分隔一行 [英] Split a line on every 16th comma

查看:211
本文介绍了每隔16个逗号分隔一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用perl从大型CSV中提取是或否,并使用此代码输出到文件中

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);

这个工作正常,输出的数据就像这个 http://pastebin.com/r7Lwwz8p ,但是我需要在第16个元素之后将
分解为一个新行,所以它看起来像这样:一个href =http://pastebin.com/xC8Lyk5R =nofollow> http://pastebin.com/xC8Lyk5R
非常感谢任何提示/技巧!

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!

推荐答案

下面的代码以逗号分隔一行,然后通过16个元素重新组合它们:

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

这篇关于每隔16个逗号分隔一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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