Home > Back-end >  Parsing through a text file and skipping lines with Powershell
Parsing through a text file and skipping lines with Powershell

Time:12-02

I have a massive text file that looks like the following:

------
Device Location: Seattle
Entry address(es):
IP address: 10.0.0.1
----------
Device Location: New York
Entry address(es):
IP address: 10.5.0.1
----------
Device Location: Las Vegas
Entry address(es):
IP address: 10.9.0.1
----------
Device Location: Seattle
Entry address(es):
IP address: 10.0.6.1
----------

Basically, I'm trying to get the IP addresses for all devices in Seattle. I'm using a foreach loop to parse through the text and find any string that has "Seattle" but once I find Seattle I don't know how to grab the IP address that is 2 lines underneath it.

Does anyone know what the solution is here?

$text = get-content textfile.txt
foreach($line in $text){
            if ($line -match "Seattle"){
               skip 1 line and grab IP
}}

Thanks in advance!

CodePudding user response:

Use the Select-String cmdlet with its -Context parameter to find lines containing the string Seattle and capture the next two lines as well.

You can then extract the IP address from the 2nd line following each match, as follows:

Select-String -Context 0, 2 -Pattern Seattle -LiteralPath textfile.txt |
  ForEach-Object { (-split $_.Context.PostContext[-1])[-1] }
  • Related