请求 csv 的 Powershell 脚本,类型的前 n 条记录

Requesting Powershell script for csv, top n records of type

有一个像这样的 csv。很想使用 powershell Import-csv

我需要每种水果的最后(或最新)3 条记录。

#foo.csv
No, Fruit, Quality, Units, Location
1, Orange, New, 10, Village
2, Orange, Fresh, 20, City
3, Apple, New, 15, Village
4, Grapes, Fresh, 25, City
5, Apple, Fresh, 30, City2
6, Apple, Fresh, 35, City1
7, Apple, Fresh, 35, City2
8, Grapes, Fresh, 30, City2
9, Grapes, Fresh, 35, City3

输出将包含苹果的第 5、6、7 行和葡萄的第 4、8、9 行,橙子的第 1、2 行等等。排序需要先按水果然后按行 ID。

$data = import-csv D:\fruits.txt
$data | group Fruit | foreach {
    $_.group | select -last 3
} | sort Fruit | ft -AutoSize

例如输出:

No Fruit  Quality Units Location
-- -----  ------- ----- --------
5  Apple  Fresh   30    City2   
6  Apple  Fresh   35    City1   
7  Apple  Fresh   35    City2   
4  Grapes Fresh   25    City    
8  Grapes Fresh   30    City2   
9  Grapes Fresh   35    City3   
1  Orange New     10    Village 
2  Orange Fresh   20    City