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

Splitting text file by specific string/keyword

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:

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

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

>Solution :

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…}
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