1

I want to create a file that contains columns from two input files. File1 is like:

s,a
k,b
h,c

File2 is:

f,a
g,b 

The output should be like:

s,a,f
k,b,g
h,c,-

am using the join command like

join  -a1 -a2 -t , -1 2 -2 2 -o auto -e "-" file1 file2 > joinoutput

am getting out put like

a,s,f
b,k,g
c,h,-

please help me to fix , I cant able to specify the order of column like -o '1.1' like. if in my first file number of column is n and second file it is n i need to see n+n -1 thanks in advance

  • 1
    Cannot give an answer for n>2 because you have not specified the output order of the fields on each line when n>2. You can even specify with the -o syntax, for example for n=3, would it be, "1.1 1.2 1.3 2.1 2.3" or "1.1 1.3 1.2 2.1 2.3" or something else? I think we may have to build the output format string after looking at the files. – RobertL Nov 20 '15 at 8:14
  • Does it have to be shell? This is pretty easy in Perl. – Sobrique Nov 28 '15 at 22:28
  • @Sobrique i dont know perl help me pls – amicos Dec 3 '15 at 11:03
0

Replace -o auto with -o '1.1 1.2 2.1'

to get:

s,a,f
k,b,g
h,c,-
  • I cant able to specify the order of column like this. if in my first file number of column is n and second file it is n i need to see n+n -1 columns ,using -o '1.1 1.2 2.1' i only get 3 columns as output – amicos Nov 20 '15 at 6:52
0

In perl something like this:

#!/usr/bin/env perl
use strict;
use warnings;

#Data Dumper is for diagnostic printing
use Data::Dumper;


#open second file for reading
open( my $file2, '<', 'sampleb.txt' ) or die $!;

#slurp this file into a hash (key value map) - reverse them, so we use
#the second value as a lookup key. 
my %key_values = reverse map {/(\w+),(\w+)/} <$file2>;
close($file2);

#print what we got in that map for diag reasons. 
print Dumper \%key_values;

 #open the first file
open( my $file1, '<', 'samplea.txt' ) or die $!;
#iterate by line
while (<$file1>) {
    chomp; #strip trailing line feed. 
    #split this line on comma
    my ( $key, $value ) = split /,/;
    #loopup "$value" in that hash we created - use that if it's defined, or '-' otherwise. 
    print join( ",", $key, $value, $key_values{$value} // '-' ), "\n";
}
close ( $file1 ); 

Outputs:

s,a,f
k,b,g
h,c,-
  • i need to pass the lookup value index directly from both files based on that i need to join as join -t , -1 2 -2 2 – amicos Dec 3 '15 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.