Home > Enterprise >  How can i replace all lines in a file with a pattern using Powershell?
How can i replace all lines in a file with a pattern using Powershell?

Time:11-23

I have a file with lines that i wish to remove like the following:

 key="Id" value=123"
 key="FirstName" value=Name1"
 key="LastName" value=Name2"
 <!--key="FirstName" value=Name3"
 key="LastName" value=Name4"-->
 key="Address" value=Address1"
 <!--key="Address" value=Address2"
 key="FirstName" value=Name1"
 key="LastName" value=Name2"-->
 key="ReferenceNo" value=765

have tried the following: `

 $values = @('key="FirstName"','key="Lastname"', 'add key="Address"');
 $regexValues = [string]::Join('|',$values) 
 $lineprod = Get-Content "D:\test\testfile.txt" | Select-String $regexValues|Select-Object -          
    ExpandProperty Line    
 if ($null -ne $lineprod)
  {
   foreach ($value in $lineprod) 
    {    
    $prod = $value.Trim()
    $contentProd | ForEach-Object {$_ -replace $prod,""} |Set-Content "D:\test\testfile.txt"
    }
 }

The issue is that only some of the lines get replaced and or removed and some remain. The output should be

key="Id" value=123"
key="ReferenceNo" value=765

But i seem to get

key="Id" value=123"
key="ReferenceNo" value=765
<!--key="Address" value=Address2"
key="FirstName" value=Name1"
key="LastName" value=Name2"-->

Any ideas as to why this is happening or changes to the code above ?

CodePudding user response:

Based on your comment, the token 'add key="Address"' should be changed for just 'key="Address"' then the concatenating logic to build your regex looks good. You need to use the -NotMatch switch so it matches anything but those values. Also, Select-String can read files, so, Get-Content can be removed.

Note, the use of (...) in this case is important because you're reading and writing to the same file in the same pipeline. Wrapping the statement in parentheses ensure that all output from Select-String is consumed before passing it through the pipeline. Otherwise, you would end up with an empty file.

$values = 'key="FirstName"', 'key="Lastname"', 'key="Address"'
$regexValues = [string]::Join('|', $values)
(Select-String D:\test\testfile.txt -Pattern $regexValues -NotMatch) |
    ForEach-Object Line | Set-Content D:\test\testfile.txt

Outputs:

key="Id" value=123"
key="ReferenceNo" value=765
  • Related