Thursday 29 December 2016

Inplace file editing in perl

In this article I demonstrated an example of editing a file inplace in perl.

Consider the situation wherein we need to make some changes to a file & write them to the same file.
If we do not do anything fancy the normal way would be to use two file handles, one for input file & another for the output file.
Then loop through the input file via the input file handle, store the results in the output file handle & store the results in the output file.
Once you're done with this you can use the rename function to overwrite the original file with the new file.

Instead of doing all this we can accomplish the requirement in an easier way.

This is a script that does in place editing taking advantage of the $^I variable & the special ARGV array.

#!/usr/bin/perl -w
#
use strict ;

my $file = "testfile" ;

##setup inplace operation##
#
@ARGV = ($file) ;

##take backup of the file##
#
$^I = '.bak' ;

##doing the inplace edit##
#
while (<>) { s/test/NEW_TEST/g ; print; }


Here, we use the file called testfile containing the following lines:

[root@cent6 ~]# cat testfile
this    is         a test               file
the     second          line    test
continueing     to              third           line a test

another test I guess

The script when executed will search & replace all instances of the wrod test with NEW_TEST.


The $^I variable stores the backup of the file as the  file name followed by the .bak extension.
We assign the filename to a scaler variable named $file.Then we assign the scaler variable $file to the array variable ARGV.
In the while loop since nothing will be specified on the prompt the value of ARGV array variable will be treated as the STDIN i.e input to the while loop.
Within the body of the while loop we mention the changes we want to the file. When the loop executes the changes are written directly to the file itself eliminating the need of a temporary file.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...