Using PowerShell to remove lines from a text file if it contains a string
Suppose you want to write that in the same file, you can do as follows:
Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)
Escape the | character using a backtick
get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt
The pipe character |
has a special meaning in regular expressions. a|b
means "match either a
or b
". If you want to match a literal |
character, you need to escape it:
... | Select-String -Pattern 'H\|159' -NotMatch | ...
You don't need Select-String
in this case, just filter the lines out with Where-Object
Get-Content C:\new\temp_*.txt |
Where-Object { -not $_.Contains('H|159') } |
Set-Content C:\new\newfile.txt
String.Contains
does a string comparison instead of a regex so you don't need to escape the pipe character, and it's also faster