5

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!

pctopgs
  • 439
  • 1
  • 4
  • 10

1 Answers1

6

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
baddy
  • 47
  • 4
Eugene
  • 10,627
  • 5
  • 49
  • 67
  • 1
    This method is iffy for me. Sometime it works, other times its like powershell just completely ignores it. – pctopgs Apr 04 '20 at 00:43
  • Can you describe in what situation it doesn't work? – Eugene Apr 04 '20 at 14:06
  • Powershell just seems to ignore the part the " Where-Object {$_ -notmatch 'Brown'} " part and just copies over the entire thing – pctopgs Apr 04 '20 at 14:57
  • @pctopgs It would be appreciated if you can provide the file you want to delete lines from and also the specific script you used. – Eugene Apr 04 '20 at 15:20
  • Works well for me, as long as the search string does not contain parentheses – which I do not understand. It is a single-quoted string, so why is it parsed? The following fails: Get-Content .\prefs.js | Where-Object {$_ -notmatch 'user_pref("calendar.registry.'} | Set-Content prefs.js – Philippp Feb 21 '22 at 05:26
  • -match and -notmatch expect a regular expression. – Doug Wilson Feb 04 '23 at 01:07