当前位置: 动力学知识库 > 问答 > 编程问答 >

Powershell repeat rows in details

问题描述:

The content of my file looks like this:

header 1

detail A

detail B

detail C

header 2

detail X

detail Y

detail Z


I need to extract the header and detail information. There should be 2 columns. Header data is in the first column, detail data in the second column.

The data following the "header" text is the actual data (i.e. in "header 1", "1" is the header value). The data following the "detail" text is the actual detail data (i.e. in "detail A", "A" is the detail value).

I would like to use PowerShell to extract the header and detail information, but the header should repeat for every detail.

For example, the first column would be the header values, and the second column would be the detail values:

  1 A

  1 B

  1 C

  2 X

  2 Y

  2 Z

I thought that it would be quite simple but I'm really struggling with it. Any help would be appreciated. TIA. Below is the closest I've come to getting the result I want, but it only returns the first value:

$data = get-content 'C:\temp\file.txt'

Switch -Regex ($Data)

{

'^header(.+)' {$Data = `[PSCustomObject]@{header=$Matches[1];detail=$DefValue}}`

'^detail(.+)' {$Data.detail = $matches[1]}

}

网友答案:

You were actually very close...

switch -File .\file.txt -Regex {
    '^header(.+)' {
        $Data = [PSCustomObject]@{
            header = $Matches[1]
            detail = $DefValue}
        }
    '^detail(.+)' {
        $Data.detail = $matches[1];
        $Data
    }

}

Changes:

  • use -file option on switch instead of Get-Content
  • modified syntax around creating new object for each header found (I suspect quotes around were not intentional)
  • and last but certainly not least: output 'product' when it's complete.

Possible additional modification:

  • removing white space before/ after value: '^header ([\S]+)'
分享给朋友:
您可能感兴趣的文章:
随机阅读: