nitin chawda
nitin chawda

Reputation: 1388

How to replace string "var num = ['asd23','asd31']" in powershell

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

Answers (1)

Moerwald
Moerwald

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

Related Questions