G'day Hossein,

Here's my take on a solution. It involves no guesswork; doesn't require filenames to be of the same length; and preserves the suffixes (which don't need to be the same or, in fact, even present). It only checks for common parts at the beginning and end of the filename: it won't try to remove any common strings from the middle.

#!/usr/bin/env perl -l use strict; use warnings; use File::Basename; my @paths = qw{hhk_1sss-(hello).txt hhk_2abc-(hello).txt hhk_3xyz-(hel +lo).txt}; my @split_paths = map { [ fileparse($_ => qr{[.]?[^.]*}) ] } @paths; my @names = map { $split_paths[$_][0] } 0 .. $#split_paths; my $common_start = get_common(@names); my $common_end = reverse get_common(map { scalar reverse } @names); for (@split_paths) { print +($_->[0] =~ /^\Q$common_start\E(.*)\Q$common_end\E$/)[0], $ +_->[2]; } sub get_common { my ($control, $compare, @rest) = @_; my $common = ''; my ($control_len, $compare_len) = map { length } $control, $compar +e; for (0 .. ($control_len < $compare_len ? $control_len : $compare_l +en) - 1) { my $control_char = substr $control, $_, 1; last if $control_char ne substr $compare, $_, 1; $common .= $control_char; } return @rest ? get_common($common, @rest) : $common; }

Sample run:

$ pm_ex_same_strings.pl 1sss.txt 2abc.txt 3xyz.txt

If you want to use pathnames with directories, just change "print +(..." to "print $_->[1], (...".

-- Ken


In reply to Re: how to guess mutual (f)phrases? by kcott
in thread how to guess mutual frases? by Hossein

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.