You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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.

Using PowerShell (Most Reliable for Large Batches)

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).
Using Notepad++ (Requires Plugin)

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

  1. Open Notepad++ and go to Plugins > Plugins Admin.
  2. Search for "PythonScript", check the box, and click Install.
  3. Restart Notepad++ after installation.

Step 2: Create and Run the Script

  1. Go to Plugins > PythonScript > New Script.
  2. 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)}")
  1. Save the script (e.g., ReplaceSearchResultWithRegex.py).
  2. 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' to encoding='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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:33:14