0

i have a csv file with thousands of rows of data, looks like this No, No, Yes, No, No, No, No, No, No, No, No, No, Yes, etc

I need to break line every 16th row and output to a new file. Perl noobie here, please help!

  • no perl required; `split -l 16 inputfile outputfileprefix` – ysth Apr 18 '14 at 02:03
  • Seems to be related to this [one](http://stackoverflow.com/questions/23145978/split-a-line-on-every-16th-comma) – msy2 Apr 18 '14 at 02:37

2 Answers2

0

One way to solve this is to use the $. variable as documented in perlvar

HANDLE->input_line_number( EXPR )

$INPUT_LINE_NUMBER

$NR

$.

Current line number for the last filehandle accessed.

Each filehandle in Perl counts the number of lines that have been read from it. (Depending on the value of $/ , Perl's idea of what constitutes a line may not match yours.) When a line is read from a filehandle (via readline() or <> ), or when tell() or seek() is called on it, $. becomes an alias to the line counter for that filehandle.

Therefore when reading a file, you can determine every 16th line by if (0 == ($. % 16))

Miller
  • 34,962
  • 4
  • 39
  • 60
0

While, I'd suggest using the $. which keeps the current line number, I don't know where your rows start.

You could keep track of the rows using a counter variable, as long as we know each line starts with yes or no;

use strict;
use warnings;

my $count = 0;
my $i = 0;
open my $fh,'>', "file$i.txt" or die "$!";

while(my $line = <>){
    chomp $line;
    unless($count%16){
        open ($fh, '>', "file$i.txt") or die "$!";
        $i++;
    }
    $count = ($line =~ /^(yes|no)/i) ? $count+1:$count; 
    print $fh "$line\n";

}

usage:

perl <script.pl> <inputfile.csv>
Gabs00
  • 1,869
  • 1
  • 13
  • 12