1

Here I am printing the contents of the file which are not matching. I want to do a vice versa, i.e. print the lines of file1 (those which are matching in file2)

#!/usr/bin/perl

# create names lookup table from first file
my %names;
while (<>) {
    (my $col1)= split / /, $_;
    $names{$col1} = 1;
    last if eof;
}

# scan second file
while (<>) {
    print if /^(\S+).*/ && not $names{$1};
}

you can refer this Question Compare two files with first column and remove duplicate row from 2nd file in shell script. I don't want to remove duplicates, I only want to print those which match with the contents of column and leave others.

1
  • Remove the not.
    – choroba
    Commented Jun 3, 2014 at 11:21

1 Answer 1

2

As @choroba pointed out int the comments, all you need to do is remove the not. Here's a slightly more sophisticated version:

#!/usr/bin/perl

## Add command line switches
use Getopt::Std;

## This hash will hold the options
my %opts;

## Read the options
getopts('d',\%opts);

# create names lookup table from first file
my %names;
while (<>) {
    ## Remove trailing newlines. This is needed
    ## for cases where you only have a single word
    ## per line.
    chomp;

    my $col1=split(/\s+/, $_);
    $names{$col1} = 1;
    last if eof;
}
# scan second file
while (<>) {
    ## Skip any lines we don't care about
    next unless /^(\S+)/;

    ## Do we want the duplicates or not?
    defined $opts{d} ? 
        do{print if $names{$1}} :
        do{print unless $names{$1}};
}

If you run the script above with the -d flag (foo.pl -d file), it will print the names found in both files and without it, it will print the names found only in the first.

Note that you could do pretty much the same thing with grep. To find the dupes:

grep -wFf file1 file2

And for the non-dupes:

grep -vwFf file1 file2

However, the above will match the patterns from file1 anywhere in file2, not only at the beginning of the line.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .