Home > Batch Scripting, Perl > Replacing text in a file using Perl

Replacing text in a file using Perl

I’ve been working with Windows Batch Scripts recently. The aim has been to create a set of scripts which will automate the installation and configuration of certain applications. I was taking in user input using the SET /P MYVARIABLE=Please enter a value: syntax at the beginning of the batch script and needed to replace existing text in a configuration file with whatever the user entered at the prompt.

You can achieve this, after a fashion, using batch scripts but it’s a bit of a pain. There is a much better, easier and quicker way to do exactly the same thing using Perl. Chances are you will already have a copy of Perl available if you have the Oracle Database installed. It can all be achieved from one line typed directly into the command prompt (no need even to create a Perl script!). Example below.

The file before

The Perl command

This will replace all instances of the string “banana” in the file test.txt with the string “apple”. The search will be case insensitive. If perl.exe is not already in your PATH, you will need to call it by explicitly specifying the path where it is located or by first adding the directory where it can be found to your PATH environment variable.

The file afterwards

Categories: Batch Scripting, Perl
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: