1

我正在尝试从文本文件中批量提取子字符串,并将这些子字符串保存到数组中。我尝试了以下变体。这会将所有选定的字符串输出到屏幕,但仅将最终输出保存到变量。有没有办法模仿 =+ 运算符的功能,以便所有项目都存储在数组中?

$FILES = ls "*.txt"
foreach($f in $FILES){
  $in=Get-Content $f
  $in | Foreach { Select-String -Path "$f" -Pattern "Ad ID" -outvariable 
  array1 }}

如果我的策略被误导,将子字符串拉入数组的总体目的是让这些文本文件的多个单独子字符串数组组成。然后我会将这些值连接到一个 csv 中。我试图拉出元素而不是重新排列文本文件,因为文本文件中的子字符串的顺序不同。例子:

txt文件一:

Ad Id: xxxx
Ad Text: blah blah
Ad placement: spaceship

txt文件二:

Ad Id: yyyy
Ad placement: zoo
Ad Text: blah blah

最终期望的结果(这部分工作除了元素的顺序)

CSV 文件

xxxx, spaceship, blah blah
yyyy, zoo, blah blah
4

3 回答 3

2

这是一种构建您正在谈论的数组的方法。我不认为这是解决这个问题的最好方法。这对结果的顺序没有任何影响,也不会创建 .csv 文件。

$FILES = Get-ChildItem -File -Filter "*.txt"

$array1 = $()

foreach($f in $FILES) {
    Get-Content -Path $f |
        Select-String -Pattern "Ad Id.*" |
        ForEach-Object { $array1 += @($_.Matches.Value) }
}

$FILES.Count

$array1.Count
$array1
于 2018-05-19T19:35:03.860 回答
1

试试这个:

$files      = ls "*.txt"
$dictionary = @{}

foreach($f in $files) {
    $in = Get-Content $f
    $in.Split([Environment]::NewLine) | ForEach-Object {
        $key,$value = $_.Split(':')
        $dictionary[$key] = $value
    }
    $dictionary['Ad Id'] + ', ' + $dictionary['Ad placement'] + ', ' + $dictionary['Ad Text'] | Out-File -FilePath '.\results.csv' -Append
}

排序输出:

$files      = ls "fil*.txt"
$dictionary = @{}
[System.Collections.Generic.List[String]]$list = @()

foreach($f in $files) {
    $in = Get-Content $f
    $in.Split([Environment]::NewLine) | ForEach-Object {
        $key,$value = $_.Split(':')
        $dictionary[$key] = $value
    }
    [void]$list.Add( $dictionary['Ad Id'] + ', ' + $dictionary['Ad placement'] + ', ' + $dictionary['Ad Text'] )
}
[void]$list.Sort()
$list | Out-File -FilePath '.\results.csv' -Append
于 2018-05-19T19:38:00.473 回答
1

另一种略有不同的方法。

  • RegEx 解析 $Line 并创建一个变量,其名称在冒号之前(不带Ad)并值后面的内容
  • 在每个处理的文件之后,vars 都作为自定义对象输出

$Data = ForEach ($File in (Get-ChildItem File*.txt)){
    $Id,$Text,$Placement="","",""
    ForEach ($Line in (Get-Content $File)){
        If ($Line -Match "AD (?<Label>.*?): (?<Value>.*)"){
            Set-Variable -Name "$($Matches.Label)" -Value $Matches.Value
        }
    }
    [PSCustomObject]@{ID        = $Id
                      Placement = $placement
                      Text      = $Text}
}
$Data
$Data | Export-CSv ".\Result.csv" -NoTypeInformation

样本输出:

ID   Placement Text
--   --------- ----
xxxx spaceship blah blah
yyyy zoo       blah blah
于 2018-05-19T21:49:39.030 回答