Perl-Python: Find & Replace Strings In A File

Xah Lee, 2005-01-26

Today we'll write a snippet that does find & replace of a given string in a file.

Python

# -*- coding: utf-8 -*-
# Python

import sys

nn = len(sys.argv)

if not nn==5:
     print "error: Proper syntax is: %s search_text replace_text in_file out_file" % 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 findtext replacetext 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.

Acknowledgement: The code is based from the Python Cookbook by Alex Martelli & David Ascher, page 121. (amazon.com↗)

Reference: Python Doc↗.

Perl

Here is a analogous code in Perl.

if (scalar @ARGV != 4) {die "Error: the ordinal of the argument set does not
 match the ordinal of the parameter specified! Unix BNF:
$0 <sstr> <rstr> 
<file id1> <file id2>\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: Find & Replace on Multiple Files with Perl


See also:


Page created: 2005-01.
© 2005 by Xah Lee.
Xah Signet