0

I am pretty new to powershell scripting.The scenario is that I have to replace the first occurrence of a string with different value and second occurrence with a different value.

So far, I have this :

  $dbS = Select-String  $repoPath\AcceptanceTests\sample.config -Pattern([regex]'dbServer =     "@DB_SERVER@"')  
write-output $dbS[0]
write-output $dbS[1]

This gives the output as :

D:\hg\default\AcceptanceTests\sample.config:5:            dbServer = "@DB_SERVER@"
D:\hg\default\AcceptanceTests\sample.config:12:            dbServer = "@DB_SERVER@"

I can see that both the occurrences are correct, and this returns a MatchInfo object.Now I need to replace the contents,I tried :

Get-Content $file | ForEach-Object { $_ -replace "dbserver",$dbS[0] } | Set-Content ($file+".tmp")
Remove-Item $file
Rename-Item ($file+".tmp") $file

But this replaces all occurence and that too with the entire path. Please help..

1 Answer 1

1

Here is what i have come up with:

$dbs = Select-String .\test.config -pattern([regex]'dbServer =     "Test1"')
$file = Get-Content .\test.config

$dbs | % {$file[$_.linenumber-1] = $file[$_.linenumber-1] -replace "Test1", "Test3" }
set-content .\test.config $file

It cycles through all results of Select-String and uses its .LineNumber Property (-1) as array index to replace the text only in that line. Next we just set the content again.

If you want to assign different Values for occurance 1 and 2 you can do this:

#replace first occurance
$file[$dbs[0].LineNumber-1] = $file[$dbs[0].LineNumber-1] -replace "Test1", "Test2"
#replace second occurance
$file[$dbs[1].LineNumber-1] = $file[$dbs[1].LineNumber-1] -replace "Test1", "Test3"

This approach obviously only works if you know how many occurances you will have and which of them you want to replace.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.