如何根据字段连接两个文件而不重新排列列顺序?

如何根据字段连接两个文件而不重新排列列顺序?

我想创建一个包含两个输入文件中的列的文件。文件1就像:

s,a
k,b
h,c

文件2是:

f,a
g,b 

输出应该是这样的:

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

我使用像这样的 join 命令

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

我出去了就像

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

请帮我修复,我无法像 -o '1.1' 这样指定列的顺序。如果我的第一个文件中的列数是 n 而第二个文件中则需要查看 n+n -1 提前致谢

答案1

-o auto用。。。来代替-o '1.1 1.2 2.1'

要得到:

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

答案2

perl这样的事情中:

#!/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 ); 

输出:

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

相关内容