如何批量重命名文件夹内文件:提取指定字符串加字符移至文件名前缀
Hey there, let's tackle these two file renaming scenarios with practical, easy-to-use solutions. I'll cover cross-platform Python scripts (perfect if you work across Windows, macOS, or Linux) and system-specific command-line tools for quick one-off tasks.
Scenario 1: Find a Specific String, Extract It + Extra Characters as Prefix
Suppose you have files like report_Q32024_final.pdf and you want to extract the string Q3 plus the following 4 characters (2024) to make the prefix Q32024_report_final.pdf. Here's how to do it:
Python Script (Cross-Platform)
This uses regular expressions to target your specific string and capture the extra characters you need:
import os import re # Configure these values to match your needs target_dir = "/path/to/your/folder" # Replace with your folder path search_str = "Q3" # The specific string to look for extra_chars = 4 # Number of additional characters to capture after the search string # Regex pattern: matches the search string plus the specified number of characters pattern = re.compile(f"({re.escape(search_str)}.{{{extra_chars}}})") for filename in os.listdir(target_dir): # Skip directories, only process files if not os.path.isfile(os.path.join(target_dir, filename)): continue match = pattern.search(filename) if match: captured_prefix = match.group(1) # Remove the captured part from the original filename (clean up leftover separators) new_filename = filename.replace(captured_prefix, "", 1).strip("_- ") # Prepend the captured prefix new_filename = f"{captured_prefix}_{new_filename}" # Rename the file os.rename( os.path.join(target_dir, filename), os.path.join(target_dir, new_filename) ) print(f"Renamed: {filename} → {new_filename}")
- How to use: Update
target_dir,search_str, andextra_charsto fit your case. The script skips folders and only renames files that match your pattern.
Scenario 2: Batch Rename Files to Move a Fixed-Format String (e.g., Date) to Prefix
Your example mentions moving 8-digit date strings like 20171202 to the start of filenames (e.g., vacation_20171202_beach.jpg → 20171202_vacation_beach.jpg). If you need to extract the date plus 4 extra characters (e.g., 20171202abcd), just adjust the regex pattern.
Python Script (Cross-Platform)
This targets 8-digit date strings (YYYYMMDD) but can be modified for other fixed patterns:
import os import re target_dir = "/path/to/your/folder" # Regex pattern for 8-digit dates (YYYYMMDD) + optional 4 extra characters # Remove the `.{4}` if you only want the date itself pattern = re.compile(r"(\d{8}.{4})") for filename in os.listdir(target_dir): if not os.path.isfile(os.path.join(target_dir, filename)): continue match = pattern.search(filename) if match: captured_prefix = match.group(1) # Remove the captured part and clean up any leftover underscores/hyphens rest_of_name = filename.replace(captured_prefix, "", 1).strip("_- ") new_filename = f"{captured_prefix}_{rest_of_name}" os.rename( os.path.join(target_dir, filename), os.path.join(target_dir, new_filename) ) print(f"Renamed: {filename} → {new_filename}")
- Modify for other patterns: If your fixed string is something else (e.g.,
ID-followed by 5 digits), change the regex to(ID-\d{5}).
Command-Line Options
Windows (PowerShell)
For the date example (move 8-digit date to prefix):
$folderPath = "C:\path\to\your\folder" Get-ChildItem -Path $folderPath -File | ForEach-Object { if ($_.Name -match '(\d{8})') { $datePrefix = $matches[1] $newName = "$datePrefix_" + $_.Name.Replace($datePrefix, "").Trim('_ -') Rename-Item -Path $_.FullName -NewName $newName Write-Host "Renamed: $($_.Name) → $newName" } }
macOS/Linux (Bash)
Using rename (note: some systems use prename for Perl-based rename):
cd /path/to/your/folder # For moving 8-digit date to prefix rename 's/^(.*?)(\d{8})(.*)$/$2_$1$3/' *
- To add 4 extra characters: Adjust the regex to
s/^(.*?)(\d{8}.{4})(.*)$/$2_$1$3/
Pro Tips:
- Always test scripts on a copy of your files first to avoid accidental data loss!
- If you need to handle file extensions carefully (e.g., don't modify the extension), split the filename into name and extension before processing.
内容的提问来源于stack exchange,提问作者rykman

