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

Hello. I am relatively new to Perl, but I just love coding in it. I know other languages, but Perl is by far my favourite. Anywho, here is my question: I am making a script where a user inputs a certain directory, the script then switches to that directory, the user then inputs the file extension of the files to be modified. I store all the file names in an array like so :  @files = <*.$fileex>; where $fileex is where the file extension is stored. I would then like to open all of these files, and make a text substitution, and then close the files. How do I go about doing this? I know how to open, and edit one file, but not multiple files.... Please help!

Replies are listed 'Best First'.
Re: Opening, and editing multiple files?
by jwkrahn (Abbot) on Nov 25, 2006 at 01:53 UTC
    perl -i.bak -pe's/old text/new text/g' directory/*.ext

    Or if you want to do that inside your Perl program:

    @ARGV == 2 or die "usage: $0 directory extention\n"; my ( $dir, $ext ) = splice @ARGV; ( $^I, @ARGV ) = ( '.bak', <$dir*.$ext> ); while ( <> ) { s/old text/new text/g; print; }
Re: Opening, and editing multiple files?
by jarich (Curate) on Nov 25, 2006 at 07:08 UTC

    You say that you know how to open and edit one file; so you can just put that code in a loop:

    # Read in all the file names: my @files = <*.$fileex>; # Go through files one at a time foreach my $file (@files) { # Open $file # edit file # close $file }

    Let us know if this doesn't solve your problem.

    jarich

Re: Opening, and editing multiple files?
by quester (Vicar) on Nov 25, 2006 at 02:00 UTC
    A far simpler way would be from the command line. A Bash script to do it would look like this...
    $ cd $1 $ perl -i -w script.pl *.$2
    See perlrun for details on the command line switches. You can include an extension after -i and it will keep backups for you, as in -i.bak for instance.
Re: Opening, and editing multiple files?
by zentara (Cardinal) on Nov 25, 2006 at 14:14 UTC
    UPDATE: added a fix to prevent TextEdit from issuing warnings

    Here is a Tk script that almost does what you want. See ztksearch. Just start it in the directory you desire, and enter the search word. You can modify it to take the dir and word on the commandline, and you could add a save function by using Tk::TextEdit instead of the Text widget.

    use Tk::TextEdit; .... $text = $f2->Scrolled('TextEdit',-scrollbars=>'se',....); $text->SetGUICallbacks([sub {}]); #prevents warnings .........
    that will add a save file menu. You could get fancy too, and bind the tab button to jump from highlighted word to the next.

    I'm not really a human, but I play one on earth. Cogito ergo sum a bum