How do I delete a line from a text file in powershell?

Viewed 3761

Suddenly I have the urge to finally get into powershell. Right now I have a way to import a text file, create a text file, and add to a file, but is there a way to delete elements from a file? For example if I have a text file:

test.txt

Quick
Brown
Fox

I can import the file with $textFile = Get-Content -Path ".\test.txt"

and I can print each element and add them to a new file with

foreach($line in $textFile)
{
    Write-Host $line
    Add-Content -Path ".\output.txt" -Value $line
}

But how can I delete or remove an element (a line) from the test.txt file? I googled for a solution but I only get results for conditions in which someone wants to delete a blank line, deleting the entire file, or how to do it in C#. I thought it would be as intuitive as the previous commands..

Thanks for the feedback!

1 Answers

Take this thread as an example, it deletes lines by reserving lines which doesn't contains specific content.

You can do the same thing by reserving the line you don't want to delete.

Get-Content .\text.txt | Where-Object {$_ -notmatch 'the-word-in-specific-line'} | Set-Content out.txt

So, if you want to delete the line containing the string Brown:

Get-Content .\test.txt | Where-Object {$_ -notmatch 'Brown'} | Set-Content out.txt
Related