J <> wrote:
> I have a file with 40000 lines. Each line is a row of data, and the fields
> are seperated by pipes ( | ). I would like to align all pipes so that the
> fields will line up.
>
> example:
>
> field1 | 100 | 1 | | |
> field2islong| | example | | 3 |
>
> would become
>
> field1 | 100 | 1 | | |
> field2islong| | example | | 3 |
>
>
> anyone have any ideas.
(untested)
use Fcntl qw/:seek/;
{
open my $FILE, '<', $file or die "can't open $file: $!";
my @lengths;
while (<$FILE>) {
my @f = split /\|/;
for (0..$#f) {
$lengths[$_] < length $f[$_]
and $lengths[$_] = length $f[$_];
}
}
my $fmt = join '|', map "%-$_s", @lengths;
seek $FILE, 0, SEEK_SET;
{
open my $OUT, '>', "$file.new"
or die "can't create $file.new: $!";
local $\ = "\n";
# or maybe "|\n", if the last field is really null
while (<$FILE>) {
print $OUT sprintf $fmt => split /\|/;
}
}
}
rename "$file.new", $file or die "can't overwrite $file: $!";
--
Although few may originate a policy, we are all able to judge it.
- Pericles of Athens, c.430 B.C.