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

Dear Masters,
I have files with extension ".output" stored within these 50 directories.
And I want to move all of them to "result" directory. Is there a simple way to do it in Perl?
~/MyPerl/ | |__ result |__ dir1 |__ dir2 |__ dir3 |__ ... |__ dir50


---
neversaint and everlastingly indebted.......

Replies are listed 'Best First'.
Re: Extracting Files from Multiple Directories
by blazar (Canon) on Aug 02, 2005 at 13:35 UTC
    Yes, there is. The first module you should look at is File::Find, available as a core module, or some of its "relatives" available from CPAN.

    Said this, your question is slightly ambiguous. For if there are duplicate filenames you may have conflicts when trying to move them into "results". If you don't care about this a very rough primer may be along these lines:

    #! /usr/bin/perl -l use strict; use warnings; use File::Find; use File::Basename; @ARGV = grep { -d or !warn "`$_': not a directory!\n" } @ARGV; die "Usage: $0 <target> <source> [<sources>]\n" if @ARGV < 2; my $target=shift; find { no_chdir => 1, wanted => sub { return unless /\.output$/; my $dest="$target/" . basename $_; rename $_, $dest or warn "Can't move `$_' to `$dest': $!\n" and return; print "`$_' => `$dest'\n"; } }, @ARGV; __END__
    Things you should particularly care about when refining this include:
    • trailing slashes: a relevant module may be File::Spec,
    • checking the destinations.
Re: Extracting Files from Multiple Directories
by Smylers (Pilgrim) on Aug 02, 2005 at 13:52 UTC

    As others have said, this can be done in Perl. But ... how many files do you have? If they will fit into the arguments list of a program then you can do this easily in the Unix shell:

    $ mv dir*/*.output result

    If that works for you, then it may be easier than coding it in Perl. (And if you need it in a script then you can always use system).

    Smylers

Re: Extracting Files from Multiple Directories
by davidrw (Prior) on Aug 02, 2005 at 13:56 UTC
    lots of command-line utility ways to do this, too (bash syntax used below):
    find ~/MyPerl/dir* -name '*.output' -exec mv '{}' ~/MyPerl/result \; for n in `seq 1 50`; do mv ~/MyPerl/dir$n/*.output ~/MyPerl/result/; d +one for f in `find ~/MyPerl/dir* | grep 'output$'`; do mv $f ~/MyPerl/resu +lt/; done
    Update: Bah. I overthought and missed the obvious one Smylers just posted: mv ~/MyPerl/dir*/*.output ~/MyPerl/result (must have had the File::Find suggestions stuck in my head)
Re: Extracting Files from Multiple Directories
by sh1tn (Priest) on Aug 02, 2005 at 14:05 UTC
    use File::Copy; use File::Find; find(sub{ push @_files, $Find::File::name }, @src_dirs); copy $_, "dst_dir/$_" for @_files;


Re: Extracting Files from Multiple Directories
by prasadbabu (Prior) on Aug 02, 2005 at 13:35 UTC

    Yes, you can do easily by using File::Find.

    my 100th post.

    Prasad