Micah Longmire
Micah Longmire

Reputation: 21

How do I select a string from a string and replace it in powershell?

I'm trying to write a powershell instance that finds and replaces each instance of text and replaces it.

UserRights "rights_wo_view"

I need to place parenthesis around the quotes. I've been trying all kinds of things, but I'm running flat.

$files = get-item C:\Users\programmer\Documents\Project\tsbrick\*.asp
foreach ($file in $files)
{(Get-Content $file)
select-string -pattern ('UserRights') 
ForEach-Object {
$_ -replace '"r','("r'
$_ -replace '"p','("p'
$_ -replace '"','");'

}  | Out-File $file}

Upvotes: 2

Views: 8642

Answers (1)

Matt
Matt

Reputation: 46730

Not the best regex but this would be a good start. You aren't specific about what the line looks like so I will assume that it is on its own line with variable whitespace and or text.

Get-ChildItem C:\temp\*.asp | ForEach-Object{
    $file = $_.FullName
    (Get-Content $file) -replace '(.*UserRights\s*)"(.*?)"(.*)','$1("$2")$3' | Set-Content $file
}

Using a regex query reduces the need for chaining those replacements and Set-Content is considered preferential over Out-File. -replace functions as an array operator so we don't need to use select-string at all for this one since you still want to keep the rest of the files content. This will look for the line with "UserRights" and then some content inside quotes. Capture the those portions and write them back to file with the added brackets.

In practice, a file with the following line:

o consequat. UserRights "rights_wo_view" Duis aute irure dolor in reprehenderi

should become this while leaving the rest of the file untouched.

o consequat. UserRights ("rights_wo_view") Duis aute irure dolor in reprehenderi

Upvotes: 3

Related Questions