john sadeghi
john sadeghi

Reputation: 79

replace a string with a regex in multiple files

I have more than 10000 text files that I want to replace the string searchResult with a regex in that specific text file using Notepad++ or PowerShell. For example here is one of the text files:

searchresult : [{"name": myRegexMatch .....}

After substitution:

myRegexMatch : [{"name": myRegexMatch .....}

The regex match is different in every file. I just want to replace searchResult in every single file with the regex in that file.

Upvotes: 0

Views: 1007

Answers (1)

HeedfulCrayon
HeedfulCrayon

Reputation: 857

This should kind of get you started

$regex = '(?<=searchresult\s:\s\[{"name":\s).*(?=})'
Get-ChildItem $pathToFiles -Recurse  | Where-Object { -not $_.PSIsContainer } |
ForEach-Object {
    $text = (Get-Content $_ -Raw)
    $value = [regex]::Match($text, $regex).Groups[1].Value
    $text -replace "searchresult",$value | Set-Content -path $_
}

Upvotes: 4

Related Questions