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

"Looping the files in directory to combine with a common file."
Hi Monks, I have some n files in directory. I need to combine two files using cat $1 $2 > $3 where $2 is the file from the directory. The $1 file is common file. The files in the directory are Test1.txt, Test2.txt,... Testn.txt. The output i.e. $3 should be with a similar name as
Final1.txt --> $1 $Test1 Final1.txt --> $1 $Test1 .... .... .... Finaln.txt --> $1 $Testn
Thanks

Replies are listed 'Best First'.
Re: Looping the files in directory to combine with a common file
by monarch (Priest) on Sep 06, 2005 at 07:36 UTC
    Sounds like homework. If this is the case, please consider donating at least US$10 to a perl cause in liu of being too lazy to have a go yourself.

    my $common = shift; if ( ! $common ) { print( "Please provide common filename as a parameter\n" ); exit( 1 ); } my @files = glob( "Test*.txt" ); if ( ! scalar(@files) ) { print( "No files found to process!\n" ); exit( 2 ); } foreach my $filename ( @files ) { next if ( $filename !~ m/^Test(\d+).txt$/ ); my $number = $1; my $outputname = "Final$number.txt"; `cat $common $filename >$outputname`; } print( "Done-diddily-un\n" ); exit( 0 );

Re: Looping the files in directory to combine with a common file
by inman (Curate) on Sep 06, 2005 at 07:35 UTC
    You can use glob with a single directory or File::Find for a directory tree.

    #! /usr/bin/perl # use strict; use warnings; use File::Find; foreach (glob('*.txt')) { print "Found $_ using glob\n"; } find(\&wanted, '.'); sub wanted { return unless /\S+\.txt/i; print "Found $_ using File::Find\n"; #Do something with $_ }
Re: Looping the files in directory to combine with a common file
by davidrw (Prior) on Sep 06, 2005 at 12:56 UTC
    a few shell (bash) solutions:
    cd some_dir for f in Test*.txt ; do cat /tmp/commonfile.txt $f > Final.$f ; done find Test*.txt -maxdepth 0 -exec cat /tmp/commonfile.txt {} > Final.{} + \; for n in `seq 1 100`; do cat /tmp/commonfile.txt Test$n.txt > Final$n. +txt ; done
    The middle one will be more portable .. note that the third one produces different final naming scheme.