检索 S3 文件名,按 3 位数字与系列中的相关图像分组,然后将系列拆分为列并将新组拆分为新行

Retrieve S3 filenames, group by 3 digit number with related images in series then split series into columns and new group into new row

我正在尝试使用 CSV 批量上传列表,但图片 URL 位于列中。

我正在使用 Amazon S3 托管图像并使用 PowerShell 检索每个文件的密钥。但是我不确定如何按它们的相关文件进行分组,然后使用诸如文本到列之类的东西来拆分?

文件具有一致的命名结构:

C2-123-1.JPG
C2-123-2.JPG
C2-123-3.JPG
C3-333-1.JPG
C3-333-2.JPG

在上面的示例中,C2-123 有三张照片,C2-333 只有两张照片,所以我希望收到如下所示的结果。

|Image Link 1|  Image Link 2|   Image Link 3|   Image Link 4|
|C2-123-1.JPG|  C2-123-2.JPG|   C2-123-3.JPG|               |
|C3-333-1.JPG|  C3-333-2.JPG|               |               |

这应该有效,您应该将 $data 替换为您从 AWS 获得的输出。

  • 使用 $data 进行测试:
$data = @'
C2-123-1.JPG
C2-123-2.JPG
C2-123-3.JPG
C3-333-1.JPG
C3-333-2.JPG
C3-333-4.JPG
C3-333-999.JPG
C3-456-2.JPG
C3-111-2.JPG
C3-999-4.JPG
'@ -split '\r?\n'
  • 首先,按最后 - 和扩展名 .jpg 之间的数字分组:
Count Name    Group
----- ----    -----
    2 1       {C2-123-1.JPG, C3-333-1.JPG}
    4 2       {C2-123-2.JPG, C3-333-2.JPG, C3-456-2.JPG, C3-111-2.JPG}
    1 3       {C2-123-3.JPG}
    2 4       {C3-333-4.JPG, C3-999-4.JPG}
    1 999     {C3-333-999.JPG}
  • 然后获取Group数组的最大元素个数
  • 最后,使用 while 循环和 $max 作为转换 [pscustomobject]
  • 的参考
# Group the files
$groups = $data | Group-Object {

    [regex]::Match(
        $_,
        '(?i)(?<=\d-)(?<imagenum>\d+)\.jpg$'
    ).Groups['imagenum'].Value

}

# Determine max number of elements
$max = $groups.Count | Measure-Object -Maximum
$index = 0

# Construct the object
$result = while($max.Maximum--)
{
    $out = [ordered]@{}
    $groups.ForEach({
        $key = 'Image Link {0}' -f $_.Name
        $out[$key] = $_.Group[$index]
    })

    [pscustomobject]$out
    $index++
}

结果将是:

PS /> $result | Format-Table


Image Link 1 Image Link 2 Image Link 3 Image Link 4 Image Link 999
------------ ------------ ------------ ------------ --------------
C2-123-1.JPG C2-123-2.JPG C2-123-3.JPG C3-333-4.JPG C3-333-999.JPG
C3-333-1.JPG C3-333-2.JPG              C3-999-4.JPG 
             C3-456-2.JPG                           
             C3-111-2.JPG    

要查看 regex 说明,您可以使用 https://regex101.com/r/kARr39/1