Compare First column of File B(Name) against first column of File A
- If matched pick second column value (Dawson)
- If not insert a space
Compare Third column of File B(Age) against second column of file A.
- If matched pick fourth column value (21)
- If not insert a space
Compare fifth column of File B(Dept) against third column of File A
- If matched pick sixth column value
- If not insert a space
Compare seventh column of File B(Sex) against fourth column of file A.
- If matched pick fourth column value (Male)
- If not insert a space
文件A数据
Name|Age|Department|Sex|
文件B数据
Name|Dawson|Age|21|Sex|Male
Name|Deepak|Age|22|Department|EEE|Sex|Male
预期输出 - 文件 C
Name|Age|Department|Sex
Dawson|21||Male
Deepak|22|EEE|Male
我在下面尝试过,但它只会取出偶数列。
awk 'BEGIN{FS=OFS="|"} {for(i=2;i<=NF;i+=2){val=(val?val OFS:"") $i};print val;val=""}' File_B.txt
最佳答案
查看我看到的输入输出数据
- 文件A是一个键列表
- 文件 B 是键 + 值组合的列表
- 输出应该有每个键的列
- 如果文件 B 中的一行没有键,则该列应为空
这可以通过散列、映射、字典等轻松解决(为您喜欢的语言选择数据结构)。这是一个在 Perl 中使用散列的解决方案:
- 从文件B中读取每一行
- 沿
|
拆分:返回一个大小均匀的列表 - 将列表分配给散列:偶数条目将是键,奇数条目将是值
- 打印出散列的内容
- 使用文件 A 中的 key 列表
- 如果键不存在则插入一个空字符串
- 用
|
连接列以生成行字符串
#!/usr/bin/perl
use warnings;
use strict;
use autodie;
die "usage: $0 <headers> <data>\n"
if @ARGV < 2;
open(my $ifh, '<', $ARGV[0]);
chomp(my $headers = <$ifh>);
close($ifh);
my @headers = split(/\|/, $headers);
open($ifh, '<', $ARGV[1]);
print "$headers\n";
while (<$ifh>) {
chomp;
my %row = split(/\|/);
print join('|',
map { $row{$_} // '' } @headers
), "\n";
}
close($ifh);
exit 0;
测试运行:
$ cat fileA.txt
Name|Age|Department|Sex|
$ cat fileB.txt
Name|Dawson|Age|21|Sex|Male
Name|Deepak|Age|22|Department|EEE|Sex|Male
$ perl dummy.pl fileA.txt fileB.txt
Name|Age|Department|Sex|
Dawson|21||Male
Deepak|22|EEE|Male
关于linux - 比较两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55414900/