Powershell : sélectionner et trier un fichier texte

la programmation


Salut,

J’ai un fichier texte test.txt avec le contenu suivant :

AAAA z 669
BBBB y 9555
AAAA z 5 
BBBB z 48
CCCC y 1166
AAAA x 67777
BBBB z 223

Je veux trouver des lignes avec “z” et trier l’ensemble résultant en fonction de la dernière colonne.

Ce que j’ai essayé :

Get-Content .\test.txt | Select-String "z" | Sort-Object { [double]$_.split()[-1] }

Cela donne l’erreur :

Sort-Object : Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] does not contain a method name
d 'split'.
At line:1 char:46
+ ... test.txt | Select-String "z" | Sort-Object { [double]$_.split()[-1] }
+                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidResult: (AAAA z 669:PSObject) [Sort-Object], RuntimeException
    + FullyQualifiedErrorId : ExpressionEvaluation,Microsoft.PowerShell.Commands.SortObjectCommand

Solution 1

Essayez de traiter le contenu comme un fichier .csv et d’utiliser Importer-Csv (Microsoft.PowerShell.Utility) – PowerShell | Microsoft Apprendre[^] pour créer un ensemble d’objets personnalisés. Vous devriez alors pouvoir trier les objets.

[edit]

Cela semble fonctionner :

PowerShell
$A = Import-Csv -Path .\test.txt -Delimiter " " -Header 'One','Two','Three'
$A | Where-Object -Property Two -Like "z" | Sort-Object { [int]$_.Three }

Attention, j’ai utilisé int plutôt que double puisque toutes les valeurs sont des nombres entiers.

[/edit]

コメント

タイトルとURLをコピーしました