powershell - Sorting dates in a textfile -


i sorting text file has following pattern:

moon|gamma|d5412|745|72|8:3:43:7:6:2016 bingo|denmark|4|4|985|12:11:43:7:12:2015 charlie|london|debb|517|10|7:15:43:6:5:2014 alpha|debra|devido|0|8745|6:33:43:23:6:2016

considering 7:3:43:7:6:2016 substring date in each line, need sort lines in ascending or descending order of dates. getting errors , unable sort text file.

first, need split string delimiter | , grab last value each line:

# index -1 last 1 $datestring = 'moon|gamma|d5412|745|72|8:3:43:7:6:2016'.split('|')[-1] 

you can use datetime.parseexact() static method parse input string sortable datetime object:

[datetime]::parseexact($datestring,'h:m:s:d:m:yyyy',[cultureinfo]::invariantculture) 

now need put argument sort-object -property:

get-content .\file.txt |sort-object -property { [datetime]::parseexact($_.split('|')[-1],'h:m:s:d:m:yyyy',[cultureinfo]::invariantculture)} 

default sort order of sort-object ascending, use -descending switch change around if need be.


if want use more terse , unix'y approach, sort on individual values of date string instead (you'll need reorder them though):

sort-object { $_.split('|')[-1].split(':')[5,4,3,0,1,2] } 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -