1

I have a text file that I need to go through line by line and delete any text that is in quotation marks and does not match one of the following values:

  • 192.168.10.1
  • 192.168.11.1
  • 192.168.12.1
  • 192.168.13.1

My initial file would look something like this:

IPADDRESS "192.168.10.1" "192.168.11.1" "192.168.12.1" "192.168.13.1" "10.0.0.1"
IPADDRESS "192.168.10.1" "192.168.11.1" "127.0.0.1" "192.168.12.1" "192.168.13.1"

and I would like my output to be similar to the following:

IPADDRESS "192.168.10.1" "192.168.11.1" "192.168.12.1" "192.168.13.1"
IPADDRESS "192.168.10.1" "192.168.11.1" "192.168.12.1" "192.168.13.1"

I've experimented with using the -replace option, regular expressions, using the trim option, using a filter, using the -match option, to varying degrees of success, but I keep hitting a brick wall...

1 Answer 1

2

You can split the line, remove unwanted parts with a regex pattern and assemble back the line:

Get-Content ip.txt | Where-Object {$_} | Foreach-Object {
   $line=$_.Split()
   $line[0] + ' ' + ($line -match '"192\.168\.1[0-3]\.1"') -join ' '
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your assistance, unfortunately I'm getting the following error when trying that code: Method invocation failed because [System.String[]] doesn't contain a method named 'Split'. Am I missing something? Also, is there anyway of combining the regex matches to search for all the four values at once? Thanks
Thanks for the edited version @shay, that's put me in the right direction for what I need. Thanks
Do you have blank lines in the file? I added a filter to ignore them. Give it a try. The regex pattern takes care of the ip range you specified.
No blank spaces, however I modified the regex to suit my exact needs, and with the help of your code it's working perfectly. I wouldn't have had a clue where to start with the split and join etc. Thanks a lot for your help

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.