gpt4 book ai didi

perl - 如何比较两个文件之间的值?

转载 作者:行者123 更新时间:2023-12-02 20:07:25 24 4
gpt4 key购买 nike

我有两个文件,其中两列以空格分隔

cat file1.txt
281475225437349 33,32,21,17,20,22,18,30,19,16,23,31
281475550885480 35,32,33,21,39,40,57,36,41,17,20,38,34,37,16,99

cat file2.txt
281475550885480 16,17,20,21,32,33,34,35,36,37,38,39,40,41
281475225437349 16,17,18,19,20,21,22,23,24,25,30,31,32,33

我想将文件 1 列 2 中的值与文件 2 列 2 中的值进行比较,以了解列 1 中的相同值。并仅打印文件 1 列 2 中存在但不存在于文件 2 列 2 中的值,反之亦然,以及列 1 中的相应值

期望的o/p

它不应打印 281475225437349 的任何内容,因为 file1 列 2 中的所有值都存在于 281475225437349 的文件 2 列 2 中

它应该只打印 281475550885480 的值,该值存在于 file1 column2 中,但不存在于 file2 column2 中。例如 281475550885480 的值 57 和 99

所以 o/p 文件如下:

cat output.txt
281475550885480 57,99

我尝试过对文件进行排序并使用 sdiff 进行比较,但它给出了差异并且需要时间

sdiff file1.txt file2.txt

最佳答案

Perl 解决方案:从第二个文件创建哈希值的哈希值。键是大数字,内部键是逗号分隔列表中的较小数字。然后迭代第一个文件并检查记住的结构中未提及哪些数字。

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

open my $f1, '<', 'file1' or die $!;
open my $f2, '<', 'file2' or die $!;

my %seen;
while (<$f2>) {
my ($key, $value_string) = split ' ';
my @values = split /,/, $value_string; #/
undef @{ $seen{$key} }{@values};
}
while (<$f1>) {
my ($key, $value_string) = split ' ';
my @values = split /,/, $value_string;
my %surplus;
undef @surplus{@values};
delete @surplus{ keys %{ $seen{$key} } };
say $key, ' ', join ',', keys %surplus
if keys %surplus;
}

顺便说一句,当你切换文件时,输出将是

281475225437349 24,25

因为 file1 中不存在 24 和 25。

关于perl - 如何比较两个文件之间的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54364389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com