wanlanman has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to compare a text list of filenames with a directory listing and copy the matches to another directory.
I'm having trouble with the compare piece.
I can read the text file of names and use opendir to open the directory, but I'm not sure how to do the compare.

Thanks for any help...
  • Comment on compare directory list with a text list of filenames

Replies are listed 'Best First'.
Re: compare directory list with a text list of filenames
by oxone (Friar) on Jul 24, 2007 at 16:39 UTC
    Hi. If you're looking for a simple way to do this in Perl, rather than using system calls and then parsing the results, then you could do it like this:

    You say you are OK reading your text file of 'wanted' filenames. When reading it I suggest you use a hash to remember them (maybe called %wanted) - so you'd do ++$wanted{ $filename } for each one (remembering to chomp the filename first if you've just read it as a line from a file).

    On to the part you're asking for help with: You can then get a list of all the files in a given directory like this:

    # Get a list of all files in a given directory # Note use of the grep to exclude subdirectory names my @files_in_dir = grep { !-d $_ } glob( "myfolder/*" ); # Strip off any leading folder names so that # myfolder/file1.txt then becomes just file1.txt s/.*[\\\/]// for @files_in_dir;

    Having done that, you can easily create a new list which is only those files which are on your 'wanted' list:

    my @matching_files = grep { $wanted{ $_ } } @files_in_dir;

    You've then got a list of filenames in @matching_files which are both in your file, and in the directory you checked.

    I suggest you should then look up File::Copy if you're not sure how to do the final part of your task.

    Note that this will compare in a case-sensitive way. If you want case-insensitivity, you should lowercase the filenames in the appropriate places above using lc().

      Excellent, thanks very much for the help!
Re: compare directory list with a text list of filenames
by halley (Prior) on Jul 24, 2007 at 15:42 UTC
    I suggest you do this outside perl with a commonly available "diff" tool, but the Perl module Algorithm::Diff would be sufficient, too. Get the file listings with a Win32 dir /s /b command, or a Un*x find command. The trick is to sort your file listings and remove any useless prefix stuff before comparing.

    --
    [ e d @ h a l l e y . c c ]

Re: compare directory list with a text list of filenames
by fmerges (Chaplain) on Jul 24, 2007 at 17:26 UTC

    Hi,

    use strict; use warnings; open my $fh, '<', 'source.txt'; my @files = <$fh>; chomp @files; print join "\n", grep { -e $_ } @files;

    Assuming the source file contains the full path to the files

    Regards,

    fmerges at irc.freenode.net