简体   繁体   English

没有标题的数据的Powershell排序对象

[英]Powershell sort-object for data without a header

Is there a way in PowerShell to sort data that does not have a header. PowerShell中是否可以对没有标题的数据进行排序。 I cannot use | sort-object dateViewed 我不能使用| sort-object dateViewed | sort-object dateViewed because my data does not contain a header. 由于我的数据不包含标头,因此| sort-object dateViewed I could use a script to create a new object with a header, but is there a way to sort by the 3rd column? 我可以使用脚本来创建带有标题的新对象,但是有没有一种方法可以按第三列进行排序?

If I have a cli API aws get-vols that returns data like: 如果我有一个cli API aws get-vols ,它返回如下数据:

disk00   123456  20180103

disk00   222222  20180101

disk00   333333  20180102

I'm looking for the easy way out. 我正在寻找简单的出路。

aws get-vols | sort-object (specify something that means column 3)

And i would see: 我会看到:

disk00   222222  20180101

disk00   333333  20180102

disk00   123456  20180103

You might be better off using the AWS PowerShell module instead, which probably returns a real object. 您最好改用AWS PowerShell模块 ,该模块可能返回真实对象。

But to answer your question, I will assume the return from aws get-vols is a bunch of separate lines, which are really just strings, where each "column" is separated by a TAB . 但是要回答您的问题,我将假设aws get-vols的返回是一串单独的行,它们实际上只是字符串,其中每个“列”都由TAB分隔。

In that case, treat it like a CSV with a special delimiter: 在这种情况下,请将其视为带有特殊定界符的CSV:

aws get-vols |
    ConvertFrom-Csv -Delimiter "`t" -Header Disk,Id,DateViewed |
    Sort-Object -Property DateViewed

You can use the same approach if the separator is multiple spaces instead of tab, it's just a little more annoying: 如果分隔符是多个空格而不是制表符,则可以使用相同的方法,只是有点烦人:

aws get-vols |
    ForEach-Object -Process {
        # replace all contiguous whitespace with a comma
        # hope you don't have column values with spaces ;)

        $_ -replace '\s+', ','  
    } |
    ConvertFrom-Csv -Header Disk,Id,DateViewed |
    Sort-Object -Property DateViewed

If you have PowerShell 5.0 or newer, you should be able to say something like this with the ConvertFrom-String cmdlet : 如果您具有PowerShell 5.0或更高版本,则应该能够使用ConvertFrom-String cmdlet这样说

aws get-vols | ConvertFrom-String | Sort-Object P3

But I agree with briantist that if there are cmdlets you should use those instead of parsing text. 但是我同意briantist的观点 ,如果有cmdlet,则应使用这些cmdlet而不是解析文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM