user2138826
user2138826

Reputation: 441

Replace a line in PERL with other line

I am iterating a file then there is a string for which I have to search for and from that string I have to replace a sub string with another string. Can anyone help me to solve this problem. I tried like this.

while(<FH>)
{
if($_ =~ /AndroidAPIEventLogging=false/i)
{

if($& =~ s/false/True/)
{
print("Changed successfully\n");

}

}

} 

Now it is showing that it can perform only read operations. I tried by opening the file in each possible mode.

Upvotes: 0

Views: 57

Answers (2)

Oleksiy
Oleksiy

Reputation: 91

You can do that using -i option via Perl one-liner

perl -i -pe 's/AndroidAPIEventLogging=false/AndroidAPIEventLogging=true/i' file1 file2...

As an alternative way, take a look at Tie::File. It seems to be designed for quick in-place file edits.

Upvotes: 0

mpapec
mpapec

Reputation: 50637

Match and substitute is some kind of perl anti-pattern, as you're matching (often same strings) two times, so back to your question

while (<FH>) {
  # everything before '\K' is not replaced (positive look behind)
  if (s/AndroidAPIEventLogging=\Kfalse/True/i) { # $_ =~ 

    print("Changed successfully\n");
  }
}

Upvotes: 2

Related Questions