1

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
2
  • Are you looking to ignore specifically IP addresses or numeric digits and literal dots? Commented May 3, 2022 at 0:46
  • @SantiagoSquarzon I got a command to write an IP address to a file so I can use it for a service like Ansible. This happens when I create my virtual machine, but when I delete this virtual machine I need it to delete the ip address from the file and I just need to provide a powershell command to remove that IP address from the file Commented May 3, 2022 at 0:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.