So I have several large text files I need to sort through, and remove all occurrences of lines which contain a given keyword. So basically, if I have these lines:
This is not a test
This is a test
Maybe a test
Definitely not a test
And I run the script with 'not', I need to entirely delete lines 1 and 4.
I've been trying with:
PS C:\Users\Admin> (Get-Content "D:\Logs\co2.txt") | Foreach-Object {$_ -replace "3*Program*", ""} | Set-Content "D:\Logs\co2.txt" but it only replaces the 'Program' and not the entire line.
4 Answers
Here's what I would do:
Get-Content .\in.txt | Where-Object {$_ -notmatch 'not'} | Set-Content out.txt Snark's line does the same, but it starts with loading all of the file into an array, which may be problematic with big files memory-wise.
5This will work:
(Get-Content "D:\Logs\co2.txt") -notmatch "not" | Out-File "D:\Logs\co2.txt" 5You could also use 'Select-String' with the -notmatch option:
Select-String 'not' .\input.txt -notmatch | % {$_.Line} | set-content output.txt I just needed to get this working and came up with the following:
$InServerName = 'SomeServerNameorIPAddress' $InFilePath = '\Sharename\SomePath\' $InFileName = 'Filename.ext' $OutServerName = 'SomeServerNameorIPAddress' $OutFilePath = '\Sharename\SomePath\' $OutFileName = 'Filename.out' $InFile = -join('\\',$InServerName,$InFilePath,$InFilename) $OutFile = -join('\\',$OutServerName,$OutFilePath,$OutFilename) $FindStr = 'some string to match on' $CompareStr = [scriptblock]::Create($FindStr) $CompareStr Get-Content $InFile | Where-Object {$_ -notmatch $CompareStr} | Set-Content $OutFile Get-Content $OutFile The key being that the 'Where-Object' using a script block (as denoted by the curly braces) requires declaring the variable in a script block creation event, hence the
$CompareStr = [scriptblock]::Create($FindStr) line.
By structuring it in this way, one can create a function, pass it a text string to partially match, perform the script block creation with the passed value, and have it work correctly.
The answers above do not correctly explain how to pass the value to be replaced within a variable.
1