Maverick
Maverick

Reputation: 587

Search and Replace the string in same file and count the number replaced

I am just trying to search a string "Kumar" and replacing that string with Mahi. But output is not coming . can any body point me where i am doing mistake.

#!/usr/bin/perl -w

use strict;

open(my $fh, "+>","test.txt") || die "File not found";
my @lines = <$fh>;

my @newlines;
my $count;
foreach my $line(@lines) {
   if($line =~/Kumar/i){   
   $line =~ s/Kumar/Mahi/ig;
   print $fh $line;
   #push(@newlines,$line);
   $count++;
   }
}

#print $fh @newlines;
close($fh);

Txt file:

Kumar Yadav vivek Kumar Yadav
qualcomm Kumar Yadav tarun Kumar sumit
adbd Kumar shahi Kumar sinha

Upvotes: 0

Views: 162

Answers (5)

brianadams
brianadams

Reputation: 233

open($fh, "<", "file.txt") or die "cannot open file:$!\n";
while( my $line = <$fh>){
   $line =~ s/Kumar/Mahi/;
   print $line ."\n";
}
close($fh);

Upvotes: 1

slayedbylucifer
slayedbylucifer

Reputation: 23512

I am just trying to search a string "Kumar" and replacing that string with Mahi

IF this is only what you need, then why not use a simple one-liner?...

$ cat test.txt 
line1
Kumar
Line2
Kumar

$ perl -i -p -e 's/Kumar/Mahi/g' test.txt 

$ cat test.txt 
line1
Mahi
Line2
Mahi

UPDATE: Question title and the problem statement has been drastically changed during the lifecycle of this post. So, this answer may not provide the correct solution anymore.

Upvotes: 3

mpapec
mpapec

Reputation: 50657

#!/usr/bin/perl

use strict;
use warnings;

$^I = "";
@ARGV = ("test.txt");

while (my $line = readline()) {

   print $line if $line =~ s/Kumar/Mahi/ig;
}

From perldoc

  • $^I

The current value of the inplace-edit extension. Use undef to disable inplace editing. Mnemonic: value of -i switch.

Upvotes: 3

Sabuj Hassan
Sabuj Hassan

Reputation: 39395

+> means truncate the file first, and then start reading. eventually you are getting nothing from the file.

+< means read the file and update as well. but new text will be placed at the end of the file.

So I guess for your purpose, you'll require two separate file handler for read and write operation. A detail about the file I/O can be found from here.

Upvotes: 0

DeVadder
DeVadder

Reputation: 1404

open(my $fh, "+>","test.txt")

This truncates the file while opening. So there is nothing to read when you come to the reading part. You should probably open it with < first, read it, close it and then open it with > for writing.

Upvotes: 1

Related Questions