powershellpowershell-2.0powershell-3.0powershell-4.0

get text inside a section and remove the empty section in PowerShell


I have a file with below content

parallel (

   {
 
       some content 1
       some content 2
       build ( 'Job3', parameter5: value5)
       some content 3
       some content 4

   }

)

parallel (

{ 

       some content 5
       some content 6
       build ( 'Job2', parameter3: value3, parameter4: value4)
   }

)


build ( 'Job1', parameter1: value1, parameter2: value2)

I need to keep only the content which is inside parallel ({ }) and remove the parallel({ }) section from the file. Note: The tricky part is t

Expected output

some content 1
some content 2
build ( 'Job3', parameter5: value5)
some content 3
some content 4
some content 5
some content 6
build ( 'Job2', parameter3: value3, parameter4: value4)
build ( 'Job1', parameter1: value1, parameter2: value2)


Solution

  • You can parse it with regex, see https://regex101.com/r/DiDgli/1 for details.

    $re = [regex] '(?mi)(?<=parallel\s*\(\s*\{)(?:\s*\b([^\r\n]+))+|(^build[^)]+\))'
    $re.Matches((Get-Content path\to\file.txt -Raw)) | ForEach-Object {
        if ($_.Groups[1].Success) {
            return $_.Groups[1].Captures.Value
        }
    
        $_.Groups[2].Value
    }