Bash脚本需求:批量将文件重命名为带u-前缀的修改时间Unix时间戳前缀格式
Got it, let's build a Bash script that does exactly what you need—adding a u-<unix-timestamp-ms> prefix to your image files based on their modification time. Here's a step-by-step solution:
Solution
Basic Script (Single Directory)
This script targets .jpg and .png files in your current working directory. You can adjust the file patterns to include other types if needed.
#!/bin/bash # Loop through JPG and PNG files (modify the glob to add more types) for file in *.jpg *.png; do # Skip the loop if no files match the pattern [ -e "$file" ] || continue # Get modification time in Unix milliseconds (Linux version) # For macOS, replace this line with: # mtime=$(stat -f "%Sm" -t "%s%N" "$file" | cut -c1-13) mtime=$(stat -c "%Y%N" "$file" | cut -c1-13) # Create the new filename with the prefix new_filename="u-${mtime} ${file}" # Rename the file (add -n to "mv" to test without making changes) mv -v "$file" "$new_filename" done
Breakdown of Key Parts:
- Loop: The
for file in *.jpg *.pngline targets your image files. Change this to*.gif *.webpor other extensions if you need to process more file types. - Pattern Check:
[ -e "$file" ] || continueprevents errors when there are no files matching a pattern (e.g., no PNGs in the folder). - Timestamp Extraction:
- On Linux,
stat -c "%Y"gets the modification time in Unix seconds, and%Nappends nanoseconds. Cutting the first 13 characters gives us seconds + 3 digits of nanoseconds (effectively milliseconds, matching your example format). - On macOS, the
statsyntax differs—use the commented line instead to get the same timestamp format.
- On Linux,
- Rename:
mv -vshows you each rename operation (remove-vif you don't want verbose output). Add-ntomv(likemv -nv) to run a dry test without actually renaming files—perfect for verifying everything works before making changes.
Recursive Version (Include Subdirectories)
If you need to process files in subdirectories too, use find instead of a simple loop:
#!/bin/bash # Recursively find JPG and PNG files, then rename them find . -type f \( -name "*.jpg" -o -name "*.png" \) -exec bash -c ' original_file="$1" # Get directory and base filename separately file_dir=$(dirname "$original_file") file_base=$(basename "$original_file") # Get modification time (adjust for macOS as before) mtime=$(stat -c "%Y%N" "$original_file" | cut -c1-13) # Build the new full path new_file="${file_dir}/u-${mtime} ${file_base}" # Rename the file mv -v "$original_file" "$new_file" ' _ {} \;
How to Use
- Save the script to a file (e.g.,
rename_with_timestamp.sh). - Make it executable:
chmod +x rename_with_timestamp.sh - Run it in the directory where your files are located:
./rename_with_timestamp.sh
内容的提问来源于stack exchange,提问作者Enigma
相关产品推荐
相关产品推荐

