HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Perl & Python: Find & Replace Strings in a File

Advertise Here For Profit

Xah Lee, 2005-01-26, 2011-02-07

This pages shows a simple example of Python and Perl scripts for find & replace strings in a file.

Python

# Python

import sys

nn = len(sys.argv)

if nn != 5:
     print "Error: number of arguments does not match.
Syntax should be: %s searchString replaceString inputFile outputFile" % sys.argv[0]
else:
     stext = sys.argv[1]
     rtext = sys.argv[2]
     input = open(sys.argv[3])
     output = open(sys.argv[4],'w')

     for s in input:
         output.write(s.replace(stext,rtext))
     output.close()
     input.close()

Save this code as “find_replace.py” and run it like this:

python find_replace.py find_string replacement_string in_file out_file

The “sys.argv” is from the module “sys”. The value of sys.argv[0] is the calling script's name itself.

Note the idiom for ‹var› in ‹file object›. It will loop thru the lines in file.

This code is based from Python Cookbook by Alex Martelli, David Ascher, page 121. amazon

Python Doc

Perl

Here is a similar code in Perl.

if (scalar @ARGV != 4) {die "Error: number of arguments does not match.
Syntax should be: $0 searchString replaceString inputFile outputFile\n"}
$stext=$ARGV[0];
$rtext=$ARGV[1];
$infile = $ARGV[2];
$outfile = $ARGV[3];
open(F1, "<$infile") or die "Error: $!";
open(F2, ">$outfile") or die "Error: $!";
while ($line = <F1>) {
     $line =~ s/$stext/$rtext/g;
     print F2 "$line";
}
close(F1) or die "Error: $!";
close(F2) or die "Error: $!";

For a full-featured script that does find-replace in Perl, see: Perl: Find & Replace on Multiple Files.

blog comments powered by Disqus