Dylan Boudreau wrote:
> 
> Here is what I am trying to do.  I want to read all the files in a
> directory searching for a specific string, if the string is found I want
> it to be either changed or deleted depending on what I enter as a
> replacement string.  I know I can do it by putting the output to a
> separate file and then just copying the new file over the old one but is
> there a way I can just change/delete that string in the original file?

The simple answer is yes you can do this with the -i command line switch
(or the $^I variable.)

perl -i -pe's/specific string/replacement string/g' *

This will modify all files in the current directory.  The -i switch does
this by using a temporary file so it doesn't actually modify the file
"in-place".  Here is an example that will do a literal in-place
modification:  (Note, that to do this it has to store the complete file
in memory.)


#!/usr/bin/perl
use warnings;
use strict;
use Fcntl qw/:seek/;


for my $file ( @ARGV ) {
    open my $fh, '+<', $file or die "Cannot open '$file' $!";

    my $size = -s $fh;
    my $ret = read $fh, $_, $size;
    $size == $ret or die "Error: expected $size bytes, could only read
$ret bytes.";

    s/specific string/replacement string/g;

    seek $fh, 0, SEEK_SET or die "Cannot seek on '$file' $!";
    truncate $fh, 0 or die "Cannot truncate '$file' $!";

    print;
    close $fh;
    }




John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to