Remove text from variable

Welcome Forums General PowerShell Q&A Remove text from variable

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

 
Participant
1 year, 1 month ago.

  • Author
    Posts
  • #81862

    Participant
    Points: 0
    Rank: Member

    Hi there, here's what i'm trying to accomplish, I have the following:
    $t = "|one|two","|three|four","|one|four","|three|two"
    I'm trying to use regex to remove first portion in above values:
    $t -replace regexvalue | select-object -unique
    ...and I want to get
    two
    four
    I know it's possible, I just can't seem to get the regex syntax right.
    Thank you

  • #81868

    Participant
    Points: 0
    Rank: Member

    You can't do that directly on an array like you are doing there. RegEx works on a string. You have to loop through the array for each string and do the regex

    Using the Pipeline will do this automatically for you since it will send one element of the array down the pipeline at a time.

    $t = "|one|two","|three|four","|one|four","|three|two"
    $t |
    Select-String -Pattern "\|([^\|]+)$" |
    Select-Object -ExpandProperty Matches |
    ForEach-Object {
        $_.Groups[1].value
    } |
    Select-Object -Unique
  • #81892

    Participant
    Points: 1
    Rank: Member

    And if you don't want to deal with regex (assuming the value you want is always in the same position) you could do it with split like this:

    $t = "|one|two","|three|four","|one|four","|three|two"
    
    $t | 
    ForEach-Object {
        $_.Split('|')[2]
    } | 
    Select-Object -Unique
  • #81905

    Participant
    Points: 0
    Rank: Member

    Wooohoooo, thank you both.

The topic ‘Remove text from variable’ is closed to new replies.