Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I delete a line from a file in Powershell?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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"

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading