0

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.

2
  • 2
    First off, please see Help Center - Asking. There are a ton of resources there on how to properly ask a question including editing help (formatting) and what you should include in your question to make it a Minimal, Complete, and Verifiable example. I can foresee many issues with what you've given us as an example and what potential answers you may receive. Ever tried to match a regex pattern with regex? It's not easy. Commented Feb 27, 2018 at 18:39
  • Your question could be much clearer if you were to provide a more detailed example with real values. Commented Feb 27, 2018 at 21:27

1 Answer 1

4

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 $_
}
Sign up to request clarification or add additional context in comments.

8 Comments

Hi. there is just one searchResult in each file
@johnsadeghi Are you just looking for the regex to match that scenario? Or do you need the powershell method of how to do it?
I can do simple find and replace string with regex manually in every file. but there is more than 10000 files and I am looking for powershell method to do it it once.
@johnsadeghi Make sure to upvote and mark this as the answer so that other people can be helped by it as well
If your text documents are large I would be careful with reading and storing the entire document in memory. If this is the case you can always go for an iterative approach across the pipeline Get-Content $_ -Raw | % { #perform replace | Set-Content -Path $_ -Append } or using the underlying .Net File\Streaming classes or at the very least reading the data in chucks, to perform this type of operation in a memory performant way.
|

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.