Click here to Skip to main content
15,918,275 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a text file test.txt with the following content:

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


I want to find lines with "z" and sort the resulting set according to last column.

What I have tried:

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


This gives 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
Posted

1 solution

Try treating the content like a .csv file and using Import-Csv (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn[^] to create a set of custom objects. You should then be able to sort the objects.

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

Note, I used int rather than double since all the values are integral numbers.

[/edit]
 
Share this answer
 
v2
Comments
Maciej Los 7-Jan-24 12:08pm    
5ed!
Richard MacCutchan 7-Jan-24 12:37pm    
Thanks, and Happy New Year.
Maciej Los 7-Jan-24 12:53pm    
Happy New Year, Richard :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900