Q:

Selectively merging file contents

I need to match two files and print only those lines that after specific character are not followed only by elements from one of the file.
eg I have two files that look like this:
 1A00.pdb_HEM_COA
 1A01.pdb_HEM
 1A05.pdb_IPM
 1A0F.pdb_GTS_4CA
 1A0G.pdb_PMP
 1A0I.pdb_2CP

and this:
COA
2CP
3CP
3HC
4CA
4CO

I want to match them and if it appears that first _ is only followed by elements from second file then don't print them (example is 1A0I.pdb_2CP). If in other lines it appears that _ is followed some other element but also by element from second file as well then just delete this element that is common in both files but print the line (example is 1A00.pdb_HEM_COA and printed line should be like 1A00.pdb_HEM). 
Does anybody has any idea how to do that?

A:

You could create a perl hash from the lines of the second file
#!/usr/bin/perl -w

use strict;

BEGIN{ $/ = $\ = "\n"; }

my $stringsfile = shift @ARGV;
open(my $fh, '<:encoding(UTF-8)', $stringsfile)
  or die "Could not open file '$stringsfile' $!";

my %h;

while (defined($_ = <$fh>)) {
    chomp $_;
    $h{$_} = 1;
}

and then split lines of the first (and subsequent) files into hyphen-separated fields, grep for those fields that are not in the hash, and join it all back together and print if the grep returns anything:
while (defined($_ = <ARGV>)) { 
    chomp $_;
    my ($x, @F) = split(/_/, $_, 0);
    my @y = grep({not $h{$_};} @F);
    print join('_', $x, @y) if @y;
}

Usage:
$ ./foo.pl file2 file1
 1A00.pdb_HEM
 1A01.pdb_HEM
 1A05.pdb_IPM
 1A0F.pdb_GTS
 1A0G.pdb_PMP

Note: if the potential matches are all at the end, then there's a much simpler approach using awk:
awk '
  BEGIN{OFS=FS="_"} 
  NR==FNR {a[$0]++; next} 
  {while ($NF in a) NF--} 
  NF>1 {print}
' file2 file1

For the sample data in your question, both approaches produce the same output.

