I have two files.File1 contains

470.2843    organism AR_0036     123    Intermediate
470.2845    organism AR_0033    456 Susceptible
903909.3    organism Naval-83   789 Resistant

and file2 contains


I want my output such that: if in file2 values do not match with file1, perl leaves those lines blank in the output file; or if it matches, then print the corresponding data of the matched line in the output file.

my $file1 = '/Users/apple/Desktop/ncbi_ab_data/new_file1';
my $file2 = '/Users/apple/Desktop/ncbi_ab_data/new_file2';
open my $fh1, '<' , $file1;
while (<$fh1>){
    my @file1 = split('\t', $_ );

        #print "$file1[0]\t";
        #print "$file1[1]\t";
        #print "$file1[2]\t";
        #print "$file1[3]\t\n";

    open my $fh2, '<' , $file2;
    while (<$fh2>){
    my @file2 = split('\t', $_ );
    #if ($file2[0] == $file1[2])
    #print "$file2[0]\n";
    if ($file2[0] = $file1[2]){
        print "$file2[0]";
        print "\t$file1[3]\n";

    #print "$file1[0]\n";
    #print "$file2[1]\n";
    #print "$file2[2]\n";
    #print "$file2[3]\n";
    #print "$file2[4]\n";

I have written this code but it doesn't work properly.

  • 1
    please add complete expected output for clarity
    – Sundeep
    Dec 12 '17 at 6:57

One can use join (for printing and matching field 4 of file1 with field 1 of file2) and sort (for producing ordered input data on field 4 and field 1 of file1 and file2, resp.) to perform the matching:

 join -o 2.1,1.3 -1 4 -2 1 <(sort -k 4 file1) <(sort -k 1 file2)

Using your sample data, it produces

 123 AR_0036
 456 AR_0033
 789 Naval-83

Regarding your script, I guess that index 2 in

 if ($file2[0] = $file1[2]){

is wrong.

  • then replace "-o 2.1,1.3" by "-a 2 -o 2.1,1.5" to get the non-matching lines in file2
    – tkrennwa
    Dec 12 '17 at 6:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.