Search code examples
perlfileterminalcombinationscomm

Apply command in terminal to all possible file combinations in a directory


Have a quick question:

I want to use one/either of the following scripts to determine the common lines between all the combinations of different files in a directory (the directory has 25 files).

$ perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2

or

$ comm file1 file2

However, I want to use the command on all of the possible bi-combinations of files (in my case that would be 300 unique file combinations).

Is there a way to modify this command line script to account for all possible combinations at the same time?

Thanks in advance for any help.


Solution

  • There is a CPAN module that can efficiently generate combitions: Algorithm::Combinatorics

    use strict;
    use warnings;
    use Algorithm::Combinatorics qw(combinations); 
    
    my @files = `ls <DIRECTORY>`;
    my $iterator = combinations(\@files, 2);
    
    while ( my $comb = $iterator->next ) {
       my ($file1, $file2) = @$comb;
       // call comparison script here
    }  
    

    There is probably a better way to solve this than what you are trying to do, but this solves your problem as asked.