Python, Perl: Find/Replace Strings in a File

By Xah Lee. Date: . Last updated: .

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

Python

# -*- coding: utf-8 -*-
# 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:
     searchStr = sys.argv[1]
     replaceStr = sys.argv[2]
     inputFile = open(sys.argv[3])
     outputFile = open(sys.argv[4],'w')

     for thisLine in inputFile:
         outputFile.write(thisLine.replace(searchStr,replaceStr))

     outputFile.close()
     inputFile.close()

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

python find_replace.py findStr replacementStr inputFile outputFile

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 was originally based from Python Cookbook by Alex Martelli, David Ascher, page 121. Buy at amazon

27.1. sys — System-specific parameters and functions — Python v2.7.6 documentation

Perl

Here is a similar code in Perl.

# -*- coding: utf-8 -*-
# perl

if (scalar @ARGV != 4) {die "Error: number of arguments does not match. Syntax should be: $0 searchString replaceString inputFile outputFile\n"}

$searchStr=$ARGV[0];
$replaceStr=$ARGV[1];
$inputFile = $ARGV[2];
$outputFile = $ARGV[3];

open(F1, "<$inputFile") or die "Error: $!";
open(F2, ">$outputFile") or die "Error: $!";

while ($line = <F1>) {
     $line =~ s/$searchStr/$replaceStr/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 String Pairs in Directory.