1

I am trying to replace a line in a text file. Here is my text file and Powershell script

Text File

String^ m5 = ss.FileMD5(a, salt);
    if (m5 != "e11621cc4370a5203423cc1d1ee8c2a7") {
        return 6;       //mismatch
    }

Powershell Script

$fl = "G:\tmp\test\test.txt"
$find = "m5 !="
$repl = 'if (m5 != "aaaaaaaa") {'
$content = (Get-Content $fl)

$line = $content | Select-String $find | Select-Object -ExpandProperty Line
if ($line -eq $null) {
  "Match Not Found"
  exit
} else {
  $content = $content | ForEach-Object { $_ -replace $line, $repl }
  $content  # print replaced content
}

It is always printing old content without replacement.

What the wrong i am doing in this script ?

1 Answer 1

4

When trying the replace your $line variable if (m5 != "e11621cc4370a5203423cc1d1ee8c2a7") { contains special regex characters that need to be escaped.

Change

$content = $content | ForEach-Object { $_ -replace $line, $repl }

to

$content = $content | ForEach-Object { $_ -replace [regex]::Escape($line), $repl }
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively you can use $content = ($content).replace($line,$repl) which treats it as plain text and not regex. String.replace() is a method where -replace is an operator
@Drew ($content).replace($line,$repl) also working fine. I will remember it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.