Powershell: seleccionar y ordenar archivos de texto

programación


Hola,

Tengo un archivo de texto test.txt con el siguiente contenido:

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

Quiero encontrar líneas con “z” y ordenar el conjunto resultante según la última columna.

Lo que he probado:

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

Esto da error:

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

Solución 1

Intente tratar el contenido como un archivo .csv y use Importar-Csv (Microsoft.PowerShell.Utility) – PowerShell | Microsoft aprende[^] para crear un conjunto de objetos personalizados. Entonces deberías poder ordenar los objetos.

[edit]

Esto parece funcionar:

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

Nota, usé int en vez de double ya que todos los valores son números enteros.

[/edit]

コメント

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