in reply to Re^8: One-liner only checking the first line of the input file
in thread One-liner only checking the first line of the input file
I wrote a module a while back that deals with issues exactly like this (where the line-endings are different than your platform). File::Edit::Portable.
Here's an example that reads the file, stores the original line endings, modifies them to the local platforms, then writes your output to a temporary file.
It then writes the modified data into a new file, input.txt.new with the original line endings. You can overwrite the original file by omitting the copy parameter in the write() method. read() can return an array of the entire file in list context instead of a file handle, and write() can accept an array reference of file contents in contents as opposed to a file handle. Only use the array technique if your file is small, as the whole thing will be put into memory.
use warnings; use strict; use File::Edit::Portable; my $rw = File::Edit::Portable->new; my $fh = $rw->read('input.txt'); my $wfh = $rw->tempfile; while (<$fh>){ chomp; my @line = split('\s+', $_); print $wfh "$line[2]\t$line[7]\n" if $line[7] > 0; } $rw->write(copy => 'input.txt.new', contents => $wfh);
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^10: One-liner only checking the first line of the input file
by 1nickt (Canon) on Nov 12, 2015 at 14:36 UTC | |
by stevieb (Canon) on Nov 12, 2015 at 16:50 UTC |