Parse single line output

Welcome Forums General PowerShell Q&A Parse single line output

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
2 years, 11 months ago.

  • Author
    Posts
  • #33923

    Participant
    Points: 0
    Rank: Member
    PS C:\> Get-Content "C:\GPS TRACKER\gps-position1.txt" 
    2016-01-15 00:21:04_41.05369631_-74.28771954_
    

    What I am trying to do is only select the values after the _.

    So from this string I would want 41.05369631 and -74.28771954. I would like to assign these values to separate variables, for example $lat and $long.

    Thanks in advance for all of your help Fellas!
    Cheers!

  • #33925

    Member
    Points: 0
    Rank: Member

    If the data is always going to be that simple, delimited form, then something like this should be fine:

    $line = Get-Content "C:\GPS TRACKER\gps-position1.txt" -TotalCount 1
    $array = $line -split '_'
    $lat = $array[1]
    $long = $array[2]
    

    (Note: At this point, $lat and $long are still strings rather than numbers, so you wouldn't be doing math with them directly. Converting to numeric types is easy, so long as the data is valid, but you might want some better parsing / validation code to make sure of that first.)

  • #33926

    Participant
    Points: 0
    Rank: Member

    First use RegEx to do pattern matching on your string. I'm using labeled capture to easily get that section of the pattern match later from the automatic $matches variable that is populated when you use the -match operator.

    $regexmatch = "2016-01-15 00:21:04_41.05369631_-74.28771954_" -match ".*_(?'lat'.*)_(?'long'.*)_"
    
    $lat = $matches['lat']
    $long = $matches['long']
    
    $lat
    $long

    Results:

    41.05369631
    -74.28771954
  • #33927

    Participant
    Points: 0
    Rank: Member

    Nice Dave, I like the simple approach.

  • #33933

    Participant
    Points: 0
    Rank: Member

    Thanks Fellas, Exactly what I need. Didn't realize it was that simple .

The topic ‘Parse single line output’ is closed to new replies.