获取部分内的文本并在PowerShell中删除空部分。

huangapple go评论61阅读模式
英文:

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

问题

以下是您要翻译的部分:

我有一个文件,内容如下:

```none
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)

我需要保留仅位于parallel({})内的内容,并从文件中删除parallel({})部分。
注意:棘手的部分是t

预期输出

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)


<details>
<summary>英文:</summary>

I have a file with below content

```none
parallel (

   {
 
       some content 1
       some content 2
       build ( &#39;Job3&#39;, parameter5: value5)
       some content 3
       some content 4

   }

)

parallel (

{ 

       some content 5
       some content 6
       build ( &#39;Job2&#39;, parameter3: value3, parameter4: value4)
   }

)


build ( &#39;Job1&#39;, 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 ( &#39;Job3&#39;, parameter5: value5)
some content 3
some content 4
some content 5
some content 6
build ( &#39;Job2&#39;, parameter3: value3, parameter4: value4)
build ( &#39;Job1&#39;, parameter1: value1, parameter2: value2)

答案1

得分: 0

你可以使用正则表达式进行解析,详细信息请参见 https://regex101.com/r/DiDgli/1。

$re = [regex] '(?mi)(?<=parallel\(\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
}
英文:

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

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

    $_.Groups[2].Value
}

huangapple
  • 本文由 发表于 2023年7月20日 10:09:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定