基于正则匹配重命名文件:移除文件名日期前缀求助
Fix: Remove Date Prefix from Filenames (Hazel-Compatible Script)
Great call on that regex—it’s exactly what we need to target those YYYY-MM-DD - prefixes. Let’s turn that into a robust shell script you can drop straight into Hazel to handle single files, no fuss.
1. The Shell Script
This script takes a single file path as input, checks for the date prefix, and renames the file to remove it. It handles spaces and special characters in filenames safely:
#!/bin/bash # Grab the file path passed in (Hazel will send this as an argument) TARGET_FILE="$1" # Make sure the file exists before doing anything if [ ! -f "$TARGET_FILE" ]; then echo "Error: File $TARGET_FILE doesn't exist." exit 1 fi # Split out the filename (without path) and its directory FILE_NAME=$(basename "$TARGET_FILE") FILE_DIR=$(dirname "$TARGET_FILE") # Use sed with your regex to strip the date prefix NEW_FILE_NAME=$(echo "$FILE_NAME" | sed -E 's/^([12][0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])) - //') # Only rename if the prefix was actually found (avoid unnecessary changes) if [ "$NEW_FILE_NAME" != "$FILE_NAME" ]; then mv "$TARGET_FILE" "$FILE_DIR/$NEW_FILE_NAME" echo "Renamed: $FILE_NAME → $NEW_FILE_NAME" else echo "No date prefix detected in $FILE_NAME—skipping." fi
2. Setting It Up in Hazel
Getting this into Hazel is straightforward:
- Open Hazel, select the folder you want to process, and create a new rule.
- Add a condition to target your files—something like
Kind is File(or narrow it down to specific extensions:Extension is JPG, DNG, PSDif you only want those types). - Add an action: Choose
Run Shell Script, then setPass input:toas arguments. - Paste the full script into the text box (keep the
#!/bin/bashline at the top).
3. Key Notes for Safety & Reliability
- Special character handling: All variables are wrapped in double quotes, so filenames with spaces, parentheses, or other weird characters won’t break the script.
- MacOS compatibility: We use
sed -Efor extended regex, which works with macOS’s default sed (Hazel runs in the system shell environment, so no extra installs needed). - No false positives: The script only renames files where it actually finds the date prefix—no accidental changes to files that don’t match.
4. Test First!
Before letting Hazel loose on all your files, test the script manually to make sure it works:
# Replace with your test file's full path ./your_script_name.sh "/Users/you/Photos/2014-10-29 - _DSF5234.DNG"
Check that the file gets renamed to _DSF5234.DNG as expected.
内容的提问来源于stack exchange,提问作者Sebastian
相关产品推荐
相关产品推荐

