Removing specific strings from a variable

This topic contains 5 replies, has 4 voices, and was last updated by Profile photo of Curtis Smith Curtis Smith 8 months ago.

  • Author
    Posts
  • #37516
    Profile photo of Vandrey Trindade
    Vandrey Trindade
    Participant

    Hi,

    I've read last month a way to do what I want, but I lost the article and can't find it =/

    I have a variable with this information gathered from a text file using Get-Content:

    Carl Marx (carl.marx@contoso.com); William Shakespeare (william.shakespeare@contoso.com); Paul Newman (paul.newman@contoso.com); Bruce Willis (bruce.willis@contoso.com)

    I want the variable to have only this:

    Carl Marx; William Shakespeare; Paul Newman; Bruce Willis

    How can I remove the "(mail@contoso.com)" information easily?

  • #37517
    Profile photo of Don Jones
    Don Jones
    Keymaster

    $var = $var -replace " ;",";"

    Would be one way.

  • #37518
    Profile photo of Vandrey Trindade
    Vandrey Trindade
    Participant

    Don Jones,

    Sorry, you must read the post as I've been trying to insert the (mail@contoso.com) text...
    I was trying using "<" to insert...

  • #37519
    Profile photo of random commandline
    random commandline
    Participant

    This example should work. Copy and paste the part you need (remove mail or add mail).

    $string = "Carl Marx (carl.marx@contoso.com); William Shakespeare (william.shakespeare@contoso.com); Paul Newman (paul.newman@contoso.com); Bruce Willis (bruce.willis@contoso.com)"
    
    # Remove mail for each
    $removemail = $string -split ';' -replace "\(.*\)",";"
    $removemail.Trim()
    # Result:  Carl Marx ;
    
    # Add mail for each
    $addmail = $string -split ';' -replace "@",".mail@"
    # Result: Carl Marx (carl.marx.mail@contoso.com)
    
  • #37523
    Profile photo of Vandrey Trindade
    Vandrey Trindade
    Participant

    random commandline,

    Thanks! Worked perfectly =]

  • #37555
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    Just something a little more simple. You can use just -replace with RegEx for this.

    $input = "Carl Marx (carl.marx@contoso.com); William Shakespeare (william.shakespeare@contoso.com); Paul Newman (paul.newman@contoso.com); Bruce Willis (bruce.willis@contoso.com)"
    $input -replace " \(.*?\)"
    

    Results:

    Carl Marx; William Shakespeare; Paul Newman; Bruce Willis
    

You must be logged in to reply to this topic.