![如何根据字段连接两个文件而不重新排列列顺序?](https://linux22.com/image/77827/%E5%A6%82%E4%BD%95%E6%A0%B9%E6%8D%AE%E5%AD%97%E6%AE%B5%E8%BF%9E%E6%8E%A5%E4%B8%A4%E4%B8%AA%E6%96%87%E4%BB%B6%E8%80%8C%E4%B8%8D%E9%87%8D%E6%96%B0%E6%8E%92%E5%88%97%E5%88%97%E9%A1%BA%E5%BA%8F%EF%BC%9F.png)
我想创建一个包含两个输入文件中的列的文件。文件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,-