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

基于正则匹配重命名文件:移除文件名日期前缀求助

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, PSD if you only want those types).
  • Add an action: Choose Run Shell Script, then set Pass input: to as arguments.
  • Paste the full script into the text box (keep the #!/bin/bash line 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 -E for 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:21:54