如何批量替换多文件中的关键词为对应文件名?
Absolutely, this is totally doable with both command-line scripts and popular text editors. Here are a few reliable methods to get this done:
Method 1: Bash + sed (Command-Line, Cross-Platform)
If you’re comfortable with the terminal, this is the fastest way to handle bulk files. A simple bash loop will iterate over your target files, extract the filename without its extension, and run the replacement automatically.
For Linux/macOS:
for file in *.php; do filename=$(basename "$file" .php) # Use this line for Linux (GNU sed) sed -i "s/myKeyword/$filename/g" "$file" # Uncomment this and comment the line above if using macOS (BSD sed) # sed -i '' "s/myKeyword/$filename/g" "$file" done
- Quick breakdown:
for file in *.php: Loops through all.phpfiles in your current directory (adjust the pattern to match your files, like*.txtorsrc/*.js)basename "$file" .php: Strips the.phpextension to get the clean filename (e.g.,file1.phpbecomesfile1)sed -i "s/myKeyword/$filename/g" "$file": Does in-place replacement of every occurrence ofmyKeywordwith the filename. Thegflag ensures all instances in the file are replaced, not just the first.
For Windows (PowerShell):
If you’re on Windows, PowerShell works just as well:
Get-ChildItem -Filter *.php | ForEach-Object { $filename = $_.BaseName (Get-Content $_.FullName) -replace 'myKeyword', $filename | Set-Content $_.FullName }
Get-ChildItem -Filter *.php: Grabs all.phpfiles in the current directory$_.BaseName: Directly retrieves the filename without its extension-replace 'myKeyword', $filename: Handles the replacement and writes the modified content back to the original file.
Method 2: Visual Studio Code (GUI)
VS Code has powerful regex find/replace that can access the current filename natively. Here’s how to use it:
- Open the folder containing your files in VS Code
- Press
Ctrl+Shift+F(Windows/Linux) orCmd+Shift+F(macOS) to open the global find panel - Type
myKeywordin the "Find" field - Click the
.*button to enable regex mode - In the "Replace" field, enter
$TM_FILENAME_BASE(this built-in variable gives the filename without its extension) - Make sure "Files to Include" is set to match your target files (e.g.,
*.php), then click the "Replace All" button (the double arrows with a checkmark)
Method 3: Sublime Text (GUI)
Sublime Text also supports this with regex and built-in variables:
- Open your project/folder in Sublime Text
- Press
Ctrl+Shift+F(Windows/Linux) orCmd+Shift+F(macOS) for global find/replace - Enter
myKeywordin the "Find" box - Enable regex mode by clicking the
.*icon - In the "Replace" box, enter
$file_base_name - Set the "Where" field to your target files (e.g.,
*.php) - Click "Replace All"
Pro tip: Always back up your files first, or test the replacement on a copy of your files before running bulk changes to avoid accidental data loss!
内容的提问来源于stack exchange,提问作者user3076396

