查找以相同值开始的对象,并在数组Powershell中只保留最长的值

qfe3c7zg  于 2023-06-06  发布在  Shell
关注(0)|答案(1)|浏览(137)

我试图找到一个解决方案来过滤我的数组。
对于标准,它将是:如果第三列的对象与同一列的另一个对象匹配(或包含)。那就删了它
下面是一个$data的例子:

By      Mode File
--      ---- ----
user1   Read creation\1. ABC
user1   Read creation\1. ABC\Invoice
user1   Read creation\1. ABC\LIMITED
user2   Read edition\File
user2   Read edition\File\DATA SHEETS
user2   Read BCD
user2   Read BCD\DATA
user3   Read BCD

我想删除具有相同开头的对象,只保留具有最多字符的对象。但是,如果不是同一用户,则不应过滤该行。
我在寻找的结果是:

By      Mode File
--      ---- ----
user1   Read creation\1. ABC\Invoice
user1   Read creation\1. ABC\LIMITED
user2   Read edition\File\DATA SHEETS
user2   Read BCD\DATA
user3   Read BCD

我尝试的是:

foreach($elem in $data.file)
{
$data.file.Where({$_.contains($elem)}, 'First',3)
}

我卡住了,谢谢你的评论

n6lpvg4x

n6lpvg4x1#

根据这些有用的注解,我相信这就是你要找的,假设我们将示例输入存储在一个名为CSV的变量中:

$csv = ConvertFrom-Csv @'
By,Mode,File
user1,Read,creation\1. ABC
user1,Read,creation\1. ABC\Invoice
user1,Read,creation\1. ABC\LIMITED
user2,Read,edition\File
user2,Read,edition\File\DATA SHEETS
user2,Read,BCD
user2,Read,BCD\DATA
user3,Read,BCD
'@

我们可以使用Group-ObjectSort-ObjectString.StartsWith的组合:

# group the objects by the `By` property and enumerate them
$csv | Group-Object By | ForEach-Object {
    # sort the groups by the `File` property (ascending)
    $sorted = @($_.Group | Sort-Object File)
    # and enumerate each group
    for($i = 0; $i -lt $sorted.Count; $i++) {
        # store the current item
        $current = $sorted[$i]
        # and the next item in this collection
        $next = $sorted[$i + 1]
        # if there is a next item in this group AND
        # the next item `File` property starts with the same string as the current item
        # i.e.: `'edition\File\DATA SHEETS'.StartsWith('edition\File')`
        if($next -and $next.File.StartsWith($current.File, [StringComparison]::InvariantCultureIgnoreCase)) {
            # we can assume this one can be skipped
            continue
        }
        # else, output it
        $current
    }
}

从这个例子中产生的输出将是:

By    Mode File
--    ---- ----
user1 Read creation\1. ABC\Invoice
user1 Read creation\1. ABC\LIMITED
user2 Read BCD\DATA
user2 Read edition\File\DATA SHEETS
user3 Read BCD

相关问题