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
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"} ; $_}
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”)}
Hi Rob - Both those examples return
Blue
Blue5
2
If you want to replace exactly the number 4, you can use the regex start string and end string operators. Ex: $_ -replace “^4$”,“Blue”