1

I have a log file with entries like

AA this is a line A

CODE C

CODE C

CODE C

AA this is a line A

CODE C

AA this is a line A

CODE C

CODE C

AA this is a line A

So I need to find the first

AA this is a line A

and grab then all corresponding CODE C below and then ideally another object with AA this is a line A and the next CODE C until the whole file is done

I have:

$codelog = 'C:\data\code.log'


$collection = get-content $codelog

$endline = Get-Content $codelog | Measure-Object -Line | Select -ExpandProperty Lines
$i = 0
$withlines = get-content $codelog | foreach{"$i $_";$i++}
$linenumbers = @()

foreach($line in $withlines)
{
    if($line -like "AA This is a line*")
     {$linematch = $line.split(' ')[0];$linenumbers += $linematch} 
     
    
}

$totallines = $linenumbers | Measure-Object -Line | select -ExpandProperty lines

$linereader = @()
$linereader = 1
foreach($code in $linenumbers)
{
    
}

I can't get my head around

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
Bert
  • 11
  • 3
  • So you just want all lines starting from the first line `AA`? Or only the lines that are not starting with `AA` _after_ the first line starting with `AA`? – Mathias R. Jessen May 03 '22 at 10:21
  • What kind of objects are you expecting? An array of arrays (lines) perhaps? – Theo May 03 '22 at 11:09

1 Answers1

0

It is not clear what the expected result should be. You talk about objects, but the example log and your code suggest you want an array of arrays (lines between the 'AA this is a line A' markers).

If that is the case, you can do this:

$codelog   = 'C:\data\code.log'
$collector = [System.Collections.Generic.List[string]]::new()
$result = switch -Regex -File $codelog {
    '^AA this is a line A' {
        if ($collector.Count) {
            # output the array we already collected
            # the unary comma in front makes result to become an array of arrays
            ,$collector.ToArray()
            $collector.Clear()
        }
    }
    default {
        if (![string]::IsNullOrWhiteSpace($_)) { $collector.Add($_) }
    }
}

# process what you now have parsed out
$result | ForEach-Object {
    # each $_ is an array
}
Theo
  • 57,719
  • 8
  • 24
  • 41