Home > Software design >  Splitting text file by specific string/keyword
Splitting text file by specific string/keyword

Time:08-18

I have a txt file like this:

GroupA
SERVER0953
SERVER93785
COMP3784523
SERVER92374
ENDOFSECTION
GroupB
SERVER840
COMP395
COMP38954
LAP89384
ENDOFSECTION
GroupC
COMP395023
SERVER8294034
COMP38483
COMP384784
LAP4834982
LAP95483
LAP38584
COMP394894
ENDOFSECTION

I want to split at ENDOFSECTION and then loop through all the elements from the previous ENDOFSECTION e.g. I want to loop through the following to add every computer from [1] to [-1] to a the group name at [0]. I want to repeat this same action for every section.

GroupA
SERVER0953
SERVER93785
COMP3784523
SERVER92374

I have this:

Get-Content c:\temp\test.txt | foreach-Object {$_.split("ENDOFSECTION") }

But it doesn't seem to work on POSH5, but does on POSH7. I need to have it work on POSH5 and how do I put this into an object/array so I can run actions against each chunk

CodePudding user response:

Use the -split operator:

  • Note: The following uses a here-string to simulate input from a file. The solution relies on the input to be single, multi-line string. Thus, with file input, use Get-Content with the
    -Raw switch (e.g., Get-Content -Raw file.txt)
@'
GroupA
SERVER0953
SERVER93785
COMP3784523
SERVER92374
ENDOFSECTION
GroupB
SERVER840
COMP395
COMP38954
LAP89384
ENDOFSECTION
GroupC
COMP395023
SERVER8294034
COMP38483
COMP384784
LAP4834982
LAP95483
LAP38584
COMP394894
ENDOFSECTION
'@ -split '\r?\nENDOFSECTION(?:\r?\n|\z)' -ne '' | # split into blocks
  ForEach-Object { # process each block
    $group, $servers = $_ -split '\r?\n' # split block into group-name and server-name lines
    # Now you can work with the group name in $group,
    # and the list of servers in $servers, e.g.:
    [pscustomobject] @{
      Group = $group
      Servers = $servers
    }
  }

Output:

Group  Servers
-----  -------
GroupA {SERVER0953, SERVER93785, COMP3784523, SERVER92374}
GroupB {SERVER840, COMP395, COMP38954, LAP89384}
GroupC {COMP395023, SERVER8294034, COMP38483, COMP384784…}
  • Related