Reputation: 1388
Replace the give string
var num = ['red222','edr223']; //this value is always changing
as below
var num = ['rev11111','rev222']; //replace with any string
Tried:
num = @('rev11111','rev222') // text present in file say file.txt
(Get-Content "C:\file.txt").Replace('var num = *',"var num = ["+(@($Num) -join ",")+"];" )| Set-Content "C:\file.txt"
This did not help much. It cant replace when the [
]
are not empty. How to replace the string. Please help!
Upvotes: 1
Views: 64
Reputation: 11254
I think you've to use the -replace
operator and not the Replace
-method of the string object. Since Replace
doesn't support Regex.
If you change to:
$Num = @('rev11111','rev222') # text present in file say file.txt
(Get-Content "C:\temp\input.txt") -replace ('var num = \[.*\]', "var num = [$(@($Num) -join ",")]") | Set-Content "C:\file.txt"
it seems to work. I also have extended the Regex to var num = \[.*\]
.
Hope that helps.
Upvotes: 2