如何用Notepad++或PowerShell批量替换万余文本文件中searchResult为对应文件内的regex
Got it, let's work through this—you’ve got over 10,000 text files, each needing the searchResult string replaced with the unique regex pattern that lives inside that exact file. I’ll break down solutions for both Notepad++ and PowerShell, since you mentioned both tools.
PowerShell is perfect here because it lets you loop through every file, extract the regex from each one individually, and handle the replacement in one go.
Step-by-Step Script
First, adjust the script to match your file structure (I’ll assume your regex is labeled with a line like regex: ^[A-Z0-9]+$—tweak the matching pattern if your regex is stored differently):
# Replace this with your target folder path $targetFolder = "C:\Your\Text\Files\Directory" # Replace with your file extension (use *.txt for text files, *.* for all files) $fileFilter = "*.txt" # Loop through all files in the folder (and subfolders, if you remove -Recurse) Get-ChildItem -Path $targetFolder -Filter $fileFilter -Recurse | ForEach-Object { # Read the entire file content $fileContent = Get-Content $_.FullName -Raw # Extract the regex pattern from the file (adjust the regex below to match your setup) # This example looks for lines starting with "regex:" and captures everything after if ($fileContent -match 'regex:\s*(.*)') { $extractedRegex = $matches[1] # Replace all instances of "searchResult" with the extracted regex $updatedContent = $fileContent -replace 'searchResult', $extractedRegex # Write the updated content back to the file (use -Encoding if your files need it) Set-Content $_.FullName -Value $updatedContent -Encoding UTF8 Write-Host "Successfully processed: $($_.Name)" } else { Write-Warning "No regex found in $($_.Name) — skipping this file." } }
Notes
- Backup first: Test this on a small subset of files before running it on all 10k+ to avoid accidental data loss.
- Adjust the regex capture: If your regex isn’t on a line starting with
regex:, modify the'regex:\s*(.*)'part to match how your regex is stored (e.g., if it’s a standalone line, use'^\s*(.*?)\s*$'to capture the entire line).
Notepad++ doesn’t have built-in logic to extract a unique value per file for batch replacement, so we’ll use the PythonScript plugin to handle this.
Step 1: Install PythonScript
- Open Notepad++ and go to Plugins > Plugins Admin.
- Search for "PythonScript", check the box, and click Install.
- Restart Notepad++ after installation.
Step 2: Create and Run the Script
- Go to Plugins > PythonScript > New Script.
- Paste the following code (adjust the folder path and regex extraction logic to match your files):
import os import re # Replace with your target folder path target_directory = r"C:\Your\Text\Files\Directory" # Replace with your file extension (e.g., ".txt") file_extension = ".txt" # Loop through all files in the directory and subdirectories for root, dirs, files in os.walk(target_directory): for filename in files: if filename.endswith(file_extension): file_path = os.path.join(root, filename) try: # Read the file content with open(file_path, 'r', encoding='utf-8') as file: content = file.read() # Extract the regex pattern (adjust this regex to match your setup) regex_match = re.search(r'regex:\s*(.*)', content) if regex_match: regex_pattern = regex_match.group(1) # Replace all "searchResult" instances updated_content = content.replace('searchResult', regex_pattern) # Write the updated content back with open(file_path, 'w', encoding='utf-8') as file: file.write(updated_content) print(f"Processed: {filename}") else: print(f"No regex found in: {filename}") except Exception as e: print(f"Error processing {filename}: {str(e)}")
- Save the script (e.g.,
ReplaceSearchResultWithRegex.py). - Run it by going to Plugins > PythonScript > Run and selecting your saved script.
Notes
- Encoding: If your files use a different encoding (like ANSI), change
encoding='utf-8'toencoding='cp1252'or the appropriate encoding for your files. - Test first: Run the script on a small test folder to make sure it works as expected before processing all your files.
内容的提问来源于stack exchange,提问作者john sadeghi

