Home > Mobile >  How can I delete a line from a file in Powershell?
How can I delete a line from a file in Powershell?

Time:05-03

I looked online and found a command similar to this

Get-Content .\aws_hosts | Where-Object {$_ -notmatch '([^\.0-9])'} | Set-Content out.txt

All that did was copy the line to an out.txt file. I'm trying to figure out how to delete a line from the .\aws_hosts file.

In my aws_hosts file, I want to specifically delete the IP address on line 2 and not the [servers] line

[servers]
35.35.35.25

Here's the linux version of what I'm trying to do (It's from a Terraform tutorial and they're using Linux, I just can't figure out how to do it using Powershell)

sed -i '/^[0-9]/d' aws_hosts

CodePudding user response:

Just use the same regex as you would with sed:

Get-Content .\aws_hosts |
  Where-Object { $_ -notmatch '^[0-9]' } | 
    Set-Content out.txt

For smallish files (which most text files are), you can simplify to:

@(Get-Content .\aws_hosts) -notmatch '^[0-9]' | Set-Content out.txt

This simplified approach - due to reading the entire input file in full up front - also allows you to write the results back to the same file, as sed -i would.

  • Related