Replacing a string in multiple files in AIX — perl vs. sed

I had an interesting situation this morning when I had to replace string ‘db2inst1’ in multiple files with another string ‘db2inst2’. I was working on an AIX server. I wanted to do an in-place replace. In-place replaces the file with new content.

I gave Linux’s in-place replace (option ‘-i in sed) a try and here is what I got:

$sed -i 's/db2inst1/db2inst2/g' *
 sed: illegal option -- i
 Usage: sed [-n] [-u] Script [File ...]
 sed [-n] [-u] [-e Script] ... [-f Script_file] ... [File ...]

Searching online, I learned that the -i option in ‘sed’ is a GNU (non-standard) extension to the ‘sed’ command. It was not part of the classic interface to ‘sed’.

An alternative was to write a simple shell script to have ‘sed’ replace the string, write the output to a temporary file (tmp.$$) and then rename this temporary file to the original file. Snippet for such a script would look like this…just add a loop to it to take this approach..

sed 's/db2inst1/db2inst2/' infile > tmp.$$
mv tmp.$$ infile

But I was lazy… More importantly, I have been secretly looking for reasons to use ‘perl’ instead of my most beloved UNIX shell scripting. I was not inclined to give it a try until now.

I was aware that working with strings is simple in Perl. I found that perl can do in-place replace with just one-line command. I wanted to give perl a chance to impress me 😉

I tested the following command command on Linux (SUSE) and AIX (7.1) and it worked like charm in both the Operating Systems.

perl -pi -e 's/db2inst1/db2inst2/g' *

In the above command, Perl reads the input file a line at a time, makes the substitution, and then writes the results back to a new file with the same name as the original file — effectively overwriting it. Perl also is installed by default when the OS is installed. Also, the ‘replace’ syntax is similar to the one in ‘sed’.

‘Perl’ will now be a ‘pearl’ in my jewel box of handy tools that simplify my DBA life. If you are already familiar with awk, sed and shell scripting, it gets easy with perl.

Happy perling…


5 thoughts on “Replacing a string in multiple files in AIX — perl vs. sed

    • Hello Howard – Yes. You could do this as shown below.

      $perl -pi.bak -e ‘s/db2inst1/db2inst2/g’ testfile

      Just use the ‘.bak’ (or whatever the original file needs to be backed up as) for extension.
      Here is an example:

      $cat testfile

      $perl -pi.bak -e ‘s/db2inst1/db2inst2/g’ testfile

      $cat testfile.bak

      $cat testfile

      Hope that helps.

Leave a Reply

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

You are commenting using your 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