[perl-python] 20050126 find replace strings in file

Xah Lee xah at xahlee.org
Wed Jan 26 14:19:00 EST 2005

© # -*- coding: utf-8 -*-
© # Python
© import sys
© nn = len(sys.argv)
© if not nn==5:
©     print "error: %s search_text replace_text in_file out_file" %
© 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
run it like this:
python find_replace.py findtext replacetext in_file out_file

the sys.argv is from sys. sys.argv[0] is the program's name itself.

note the idiom
"for variable_name in file_object"

note that since this code reads each
line in turn, so huge file is of no-problemo

the code is based from Python
Cookbook of Alex Martelli & David
Ascher, page 121

in Python terminal, type help() then
'FILES' and or 'sys'
for reference.

try to modify this file for your
In perl, similar code can be achieved.
the following code illustrates.

if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 <sstr> <rstr>
<file id1> <file id2>\n"}
$infile = $ARGV[2];
$outfile = $ARGV[3];
open(F1, "<$infile") or die "Perl fucked up. Reason: $!";
open(F2, ">$outfile") or die "Perl fucked up. Reason: $!";
while ($line = <F1>) {
$line =~ s/$stext/$rtext/g;
print F2 "$line\n";
close(F1) or die "Perl fucked up. Reason: $!";
close(F2) or die "Perl fucked up. Reason: $!";
 xah at xahlee.org

More information about the Python-list mailing list