2

我有 4 个文件,想知道与其他文件中的元素相比不重叠的元素(每个文件)。

文件 A

Vincy
ruby
rome

文件 B

Vincy
rome
Peter

文件 C

Vincy
Paul
alex

文件 D

Vincy
rocky
Willy

对 perl、python、shell、bash 中的一个衬里的任何建议。预期的输出是:

文件 A: ruby, 文件 B: Peter, 文件 C: Paul,Alex文件 D: rocky, Willy.

4

4 回答 4

10

问题澄清后编辑:所有文件中的唯一元素,以及它出现的文件:

cat File_A File_B File_C File_D |sort | uniq -u | while read line ; do file=`grep -l $line File*` ; echo "$file $line" ; done

编辑:

如果文件很大,这样做会更快:

#!/usr/bin/perl

use strict;
use autodie;

my $wordHash ;

foreach my $arg(@ARGV){
    open(my $fh, "<", $arg);
    while(<$fh>){
        chomp;
        $wordHash->{$_}->[0] ++;
        push(@{$wordHash->{$_}->[1]}, $arg);
    }
}

for my $word ( keys %$wordHash ){
    if($wordHash->{$word}->[0] eq 1){
        print $wordHash->{$_}->[1]->[0] . ": $word\n"
    }
}

执行为:myscript.pl filea fileb filec ... filezz

澄清之前的东西: 使用 shell 命令很容易。所有文件中的非重复元素

cat File_A File_B File_C File_D |sort | uniq -u

所有文件中的唯一元素

cat File_A File_B File_C File_D |sort | uniq

每个文件的唯一元素(编辑感谢@Dennis Williamson)

for line in File* ; do echo "working on $line" ; sort $line | uniq ; done
于 2012-06-21T15:00:28.523 回答
4

这是一个快速的 python 脚本,可以对任意数量的文件执行您所要求的操作:

from sys import argv
from collections import defaultdict

filenames = argv[1:]
X = defaultdict(list)
for f in filenames:
    with open(f,'r') as FIN:
        for word in FIN:
            X[word.strip()].append(f)

for word in X:
    if len(X[word])==1:
        print "Filename: %s word: %s" % (X[word][0], word)

这给出了:

Filename: D word: Willy
Filename: C word: alex
Filename: D word: rocky
Filename: C word: Paul
Filename: B word: Peter
Filename: A word: ruby
于 2012-06-21T15:14:48.807 回答
1

热针:

import sys
inputs = {}
for inputFileName in sys.args[1:]:
  with open(inputFileName, 'r') as inputFile:
    inputs[inputFileName] = set([ line.strip() for line in inputFile ])
for inputFileName, inputSet in inputs.iteritems():
  print inputFileName
  result = inputSet
  for otherInputFileName, otherInputSet in inputs.iteritems():
    if otherInputFileName != inputFileName:
      result -= otherInputSet
  print result

不过没试过;-)

于 2012-06-21T15:16:20.460 回答
1

Perl 单行、可读版本,带有注释:

perl -nlwe '     
    $a{$_}++;     # count identical lines with hash
    push @a, $_;  # save lines in array
    if (eof) { push @b,[$ARGV,@a]; @a=(); }   # at eof save file name and lines
    }{ # eskimo operator, executes rest of code at end of input files
    for (@b) { 
        print shift @$_;                      # print file name
        for (@$_) { print if $a{$_} == 1 };   # print unique lines
    }
' file{A,B,C,D}.txt

注意:eof适用于每个单独的输入文件。

复制/粘贴版本:

perl -nlwe '$a{$_}++; push @a, $_; if (eof) { push @b,[$ARGV,@a]; @a=(); } }{ for (@b) { print shift @$_; for (@$_) { print if $a{$_} == 1 } }' file{A,B,C,D}.txt

输出:

filea.txt
ruby
fileb.txt
Peter
filec.txt
Paul
alex
filed.txt
rocky
Willy

备注:这比预期的要棘手,我相信有办法让它更漂亮,但我现在会发布这个,看看我是否可以清理它。

于 2012-06-21T15:33:44.540 回答