script to combine colums from multiple files

Madison Kelly linux-5ZoueyuiTZhBDgjK7y7TUQ at public.gmane.org
Fri Sep 12 15:03:28 UTC 2008


Neil Watson wrote:
> How would I go about cutting selected columns from multiple files and
> combining them into single file?  I so used to processing files line by
> line that this problem escapes me.
> 

Should be pretty easy... How are the columns separated (CSV?) and how do 
you want to join them? Can you give a small example of what you might be 
reading and what you want the results to be?

In perl, I might do something like:

-=-=-=-=-=-
my %cols=();
my @lines=();
open(READ, "</path/to/file.txt") or die "Can't read... $!\n";
while (<READ>)
{
	chomp;
	my @cols=split/,/;
	# Grab the first and third column.
	push @{$cols{a}}, $cols[0];
	push @{$cols{b}}, $cols[2];
}
close READ;

open(READ, "</path/to/file2.txt") or die "Can't read... $!\n";
while (<READ>)
{
	chomp;
	my @cols=split/,/;
	# Grab the second and fourth column.
	push @{$cols{c}}, $cols[1];
	push @{$cols{d}}, $cols[3];
}
close READ;

open(WRITE, "</path/to/file2.txt") or die "Can't read... $!\n";
foreach my $line (@lines)
{
	# $col will be an array ref
	print WRITE "${$cols{a}}, ${$cols{b}}, ${$cols{c}}, ${$cols{d}}\n";
}

exit 0;
-=-=-=-=-=-

Note that I've not run this so there may be errors, but hopefully it 
will get you started.

Madi
--
The Toronto Linux Users Group.      Meetings: http://gtalug.org/
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists





More information about the Legacy mailing list