简体   繁体   中英

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

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!

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

In case you want to delete the second line:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM