Problem with -replace

Tagged: 

This topic contains 5 replies, has 4 voices, and was last updated by Profile photo of Monte Hazboun Monte Hazboun 2 years, 1 month ago.

  • Author
    Posts
  • #26170
    Profile photo of PowerShell84
    PowerShell84
    Participant

    Hi powershell,
    I am facing issue with -replace. here is my sample script as below.

    Get-Content aa.txt | ForEach-Object { $_ -replace 4,"Blue"}

    where aa.txt:
    4
    45
    2

    I run it and display output like this:
    Blue
    Blue5
    2

    you see "Blue5" in the output. "45" should not be replaced in it. So how do i fix it?
    Any idea?

    I am waiting for your response

    Thanks

  • #26172
    Profile photo of Dalmiro Grañas
    Dalmiro Grañas
    Participant

    Hi there,

    The -replace operator looks for patterns rather than exact strings. So as far as i know, -replace is not gonna get you where you want.

    This line of code will change the string as expected (but it wont change the actual content of aa.txt)

    Get-Content aa.txt | ForEach-Object { if($_ -eq 4){$_ = "blue"} ; $_}
    
  • #26181
    Profile photo of PowerShell84
    PowerShell84
    Participant

    Working well. Thanks

  • #26192
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    Replace will work for what you are doing, but you need to provide both values as strings.

    Get-Content aa.txt | ForEach-Object { $_ -replace "4","Blue"}

    If you use the -replace operator,it is based off of [regex]::replace() so you can do advanced regular expression pattern replaces. Additionally, you can use the .Replace method as well for simple replace this with that logic:

    Get-Content aa.txt | ForEach-Object { $_.Replace("4","Blue")}

  • #26229
    Profile photo of Dalmiro Grañas
    Dalmiro Grañas
    Participant

    Hi Rob – Both those examples return

    Blue
    Blue5
    2
    
  • #26384
    Profile photo of Monte Hazboun
    Monte Hazboun
    Participant

    If you want to replace exactly the number 4, you can use the regex start string and end string operators. Ex: $_ -replace "^4$","Blue"

You must be logged in to reply to this topic.