Read content from file and find full file-name on disk

perlshell

My problem is that I have a bunch of file names without the version appended (version keeps changing everytime). The file names are in a file in a particular sequence and I need to get the latest version from a folder and then sequentially install the same. The logic would be:

  1. scan a file with contents
    • read a line from the file
    • using this as a key, access the folder and match the same
    • if found, write the full file-name to a file with some characters appended
    • if not found, skip and loop to line 1, till all the lines in the file are finished

What is the best language to use: shell script or Perl for such a task? And if someone can provide some hints in the form of code 🙂

Best Solution

I would read in all your partial filenames then loop through the folder matching the full filenames against the partial ones. The exact implementation would depend on some details. Do the full filenames need to appear in the same order as the partial ones did? Can you derive the partial filename from the full filename?

Update: so, something like (assuming $infile, $outfile, and $indir are already opened file and dirhandles, and a translation routine partial_filename_from_full that returns undef for things like directories or non-relevant files):

chomp( my @partial_filenames = readline( $infile ) );

while ( my $filename = readdir( $indir ) ) {
    my $partial_filename = partial_filename_from_full( $filename );
    if ( defined $partial_filename ) {
        $full_filename{ $partial_filename } = $filename;
    }
}

for my $partial_filename ( @partial_filenames ) {
    if ( exists $full_filename{ $partial_filename } ) {
        print $outfile $full_filename{ $partial_filename }, "\n";
    } else {
        # error? just skip it? you decide
    }
}

If there are multiple full filenames per partial filename, instead of assigning:

        $full_filename{ $partial_filename } = $filename;

you would determine if $filename were a better "match" than the previously encountered one.