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!
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!
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 (viareadline()
or<>
), or whentell()
orseek()
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))
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>