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

Newbie (me) asks. Can perl do this easily, or should I investigate doing this in C (have little or no ability in both).

I have a series of ascii files, like file0037.txt file0038.txt file0039.txt etc.
I have a statement somewhere within every file that goes like: Select * from stuff into selection

How do I modify/replace this statement in each file to reflect the last 2 digits of the filename?

file0037.txt - should contain
Select * from stuff where thing="37" into selection
file0038.txt - should contain
Select * from stuff where thing="38" into selection
file0039.txt - should contain
Select * from stuff where thing="39" into selection

...(thanks for your comments and/or an example script).

Replies are listed 'Best First'.
Re: Get filename inside each file
by broquaint (Abbot) on Oct 08, 2003 at 09:59 UTC
    If your data is in a simple and predictable format (i.e was generated) then a perl one-liner ought do the trick
    perl -pi.bak -e '/from stuff/ or next; ($d)=$ARGV=~/(\d\d)\.txt$/; \ s/from stuff/$& where thing = "$d"/' *.txt
    So that will replace every line containing the string 'from stuff' in every .txt file in the current directory with 'from stuff where thing = "$d"', where $d is the last two digits of the filename. See. perlrun for info on perl's command-line options, perlre for info on perl's regular expressions and perlvar for info on the $& variable.
    HTH

    _________
    broquaint

Re: Get filename inside each file
by Abigail-II (Bishop) on Oct 08, 2003 at 11:49 UTC
    system qq !echo 'Select * from stuff where thing = "@{[/(..)\./g]}" into selecti +on' > $_! for @ARGV;
    And call the program with the files to modify as arguments.

    Abigail

Re: Get filename inside each file
by Melly (Chaplain) on Oct 08, 2003 at 12:18 UTC
    use strict; my @files = glob "file*.txt"; my $file; foreach $file(@files){ if($file =~ /^file(\d{4})\.txt$/){ my $num = $1; $num =~ s/^0*//; open(IN, $file)||die "cannot open $file for read:$!\n"; open(OUT, ">tmp.txt")||die "cannot open tmp.txt for write:$!\n"; while(<IN>){ s/stuff into/stuff where thing="$num" into/i; print OUT; } close IN||die "cannot close $file:$!\n"; close OUT||die "cannot close tmp.txt:$!\n"; rename('tmp.txt', $file); } }
    Tom Melly, tom@tomandlu.co.uk
Re: Get filename inside each file
by bart (Canon) on Oct 08, 2003 at 11:19 UTC
    Not very helpful, but I have to say it: Perl originally was created to solve this kind of problems. Don't even think of writing a (throwaway) C program for it, especially if you're new to C.