【问题标题】:Powershell: Extract several strings from txt and create table out of itPowershell:从txt中提取几个字符串并从中创建表
【发布时间】:2020-11-11 12:31:49
【问题描述】:

我需要使用分布在许多 txt 文件中的值创建一个 csv 文件。这是其中一个 txt 文件的示例(它们都以相同的方式格式化并存储在一个文件夹中,比如说 c:\user\txtfiles):

System: asdf
Store: def
processid: 00001
Language: english
prodid: yellowshoes12
email: asdf@asdf.com
prodid: blueshoes34
some
other
text blabla

结果 csv 应如下所示(我添加了另一个示例 txt 中的值只是为了清楚起见):

processid, prodid
00001, yellowshoes12
00001, blueshoes34
00002, redtshirt12
00002, greensocks34

这意味着 txt 中的每个产品 ID 都应分配给 txt 中的一个 processid,并作为单行添加到 csv。

我试图达到如下结果:

$pathtofiles = Get-ChildItem  c:\user\txtfiles | select -ExpandProperty FullName
$parsetxt = $pathtofiles | 
    ForEach { 
        $orderdata = Import-Csv $_  |
        Where-Object {($_ -like '*processid*') -or ($_ -like '*prodid*')} |
        foreach {
        
        write-output $orderdata -replace 'processid: ','' -replace 'prodid: ',''
        }
    }
      $orderdata

所以我的意图是隔离相关行,删除所有不需要的内容,将值分配给变量并从中构建一个表。一个问题是,如果我将代码末尾的 $orderdata 替换为第一个 foreach 循环的末尾,则不会打印任何内容。但经过深思熟虑后,我不确定我的方法是否是一个好的方法。因此,任何帮助将不胜感激!

丹尼尔

【问题讨论】:

  • 您需要解析文本,因为这些文件未格式化为使用Import-Csv

标签: string powershell export-to-csv


【解决方案1】:

我认为最好在遍历文件夹中的文件时使用 switch -Regex -File 构造来完成。

# get the files in the folder and loop over them
$result = Get-ChildItem -Path 'c:\user\txtfiles' -Filter '*.txt' -File | ForEach-Object {
    # the switch processes each line of a file and matches the regex to it
    switch -Regex -File $_.FullName {
        '^processid:\s+(\d+)' { $id = $matches[1] }
        '^prodid:\s+(\w+)' { [PsCustomObject]@{'processid' = $id; 'prodid' = $matches[1]}}
    }
} | Sort-Object processid, prodid

# output on console screen
$result

# output to CSV file
$result | Export-Csv -Path 'c:\user\txtfiles\allids.csv'

屏幕上的结果:

processid prodid       
--------- ------       
00001     blueshoes34  
00001     yellowshoes12
00002     greenshoes56 
00002     purpleshoes88

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2013-01-10
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多