I have to do stuff like this fairly often with a bunch of different format files so I just keep this around as a generic framework. I modify the regex statements, delimiter and number of fields as necessary but it's pretty much the same program every time.
Here's what I use - lifted almost completely from various posts here on PM...
#!/usr/bin/perl
use warnings;
use strict;
open INFILE, "< $ARGV[0]"
or die "Could not open file $ARGV[0]: $!";
until(eof INFILE) {
my $fn = $ARGV[0];
open OUTFILE, "> $fn.filtered"
or die "Could not open file $fn.filtered $!";
while(<INFILE>) {
my @line = split /\t/;
$line[0] =~ s/(.{1,6}).*/$1/;
$line[3] =~ s/(.{1,6}).*/$1/;
$line[6] = $line[6]."\n";
$_ = join("\t", $line[0], $line[1], $line[2], $line[3], $line[
+4], $line[5], $line[6]);
print OUTFILE;
}
}
BTW, this code processed an 8 million line/385 mb file in about 33 minutes the other day on my old, anemic Sun Ultra 5 workstation. No brownouts, no sweat. System load never got above 1.05.
Jack
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.