Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: In-place file manipulation

by atnonis (Monk)
on Apr 30, 2003 at 16:22 UTC ( [id://254362]=note: print w/replies, xml ) Need Help??


in reply to In-place file manipulation

Hello this is one way to do it! it works for me
#!/usr/bin/perl -w use strict; die "usage: $0 <file> <search pattern> <replace pattern>", unless @ARGV == 3; my $searchFile = $ARGV[0]; my $searchPattern = $ARGV[1]; my $replacePattern = $ARGV[2]; my $tempFile = 'tmp$$'; open FILE, $searchFile #opens file in read-only mode or die "Cannot open $searchFile in read-only mode. $!\n"; open TMP, '>'.$tempFile or die "Cannot create temp file. $!\n"; while (<FILE>) { chomp; if (/$searchPattern/i) { print "Match found...replacing at line $.\n"; $_ =~ s/$searchPattern/$replacePattern/i; print TMP $_."\n"; }else { print TMP $_."\n" } } close FILE; close TMP; unlink $searchFile; rename $tempFile, $searchFile;


Antonis!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://254362]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-20 02:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found