Author Posts

June 8, 2015 at 8:45 pm

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

June 8, 2015 at 9:31 pm

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"} ; $_}

June 9, 2015 at 1:21 am

Working well. Thanks

June 9, 2015 at 4:51 am

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")}

June 9, 2015 at 4:10 pm

Hi Rob – Both those examples return

Blue
Blue5
2

June 12, 2015 at 6:44 am

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