Сначала соберите список имен изображений:
ls *jpg | gawk -F_ '{print $2}' | sort | uniq
Теперь пропустите их через montage:
ls *jpg | gawk -F_ '{print $2}' | sort | uniq | 
 while read n; do montage *\_$n\_* IMAGE_$n.jpg; done
Это предполагает, что ваши имена файлов не содержат пробелов или других странных символов. Я не уверен в вашем "идеальном" случае. Если вы обновите свой вопрос, чтобы показать свой "идеальный" результат, я смогу кое-что для вас решить.
Обновить:
Это я написал крошечный Perl-скрипт, который должен делать то, что вам нужно:
#!/usr/bin/env perl
my %k;             ## declare the hash that will store the image names
while(<>){         ## loop through STDIN
    chomp;         ## remove newline (\n)
    @a=split(/_/); ## split the line on '_' and save as array @a
    ###################################################
    # Since the image names can have varying numbers  #
    # of "_", we want to use the penultimate item in  #
    # the array ($a[$#a-1]) as the image name prefix  #
    ###################################################
    $a[$#a-1]=~s/\d*//g;
    #############################################################
    # Now that we have the prefix ('A' or 'B' in your example), #
    # we will save this image name in the hash of that prefix   #
    #############################################################
    $k{$a[$#a-1]}{$_}=1;
}
## The keys of the hash '%k' are all the prefixes we have found
foreach my $prefix (keys(%k)){
    @images=keys(%{$k{$prefix}});   ## all the images with this prefix
    ## Print the montage command to be executed (testing)
    print "montage @images -title $prefix -tile 4x $prefix.jpg\n";
    ##############################################################
    # If the commands printed above are correct, uncomment this  #
    # line to execute them instead of only printing.             #
    ##############################################################
    #`montage @images -title $prefix -tile 4x $prefix.jpg`
}
Вы можете сохранить его как foo.pl или как угодно и запустить его так:
ls *jpg | perl foo.pl
Или вы можете запустить его как один лайнер:
ls *jpg | perl -e 'my %k; while(<>){chomp; @a=split(/_/); $a[$#a-1]=~s/\d*//g; $k{$a[$#a-1]}{$_}=1;} foreach my $prefix (keys(%k)){@images=keys(%{$k{$prefix}}); `montage @images -title $prefix -tile 4x $prefix.jpg`;}'
ВАЖНО: Этот скрипт очень прост и не будет работать, если ваши имена файлов содержат пробелы или другие странные символы. Я предполагаю, что это не проблема для вас, это относительно легко исправить, но делает синтаксис более сложным вокруг.