交换文件与目录名称:批量调整文件存储路径的技术问询
Solution to Swap Date-Time and Filename in File Paths
Absolutely, this is totally doable with a straightforward shell script—ideal for handling your ~1000 files across 100 unique filenames efficiently. Here's a step-by-step approach tailored to your needs:
Step 1: Break Down the Path Swap
Your source files follow this structure:
./{date-and-time}/fixed/path/{filename}
We need to relocate each file to:
./{filename}/{date-and-time}/{filename}
Step 2: Shell Script Implementation
Save this as move_files.sh, make it executable, and run it from the parent directory of your date-and-time folders:
#!/bin/bash # Base directory where your source files live (adjust if needed) base_dir="./" # Find all files matching your path pattern find "$base_dir" -type f -path "*/fixed/path/*" | while read -r file_path; do # Extract the {date-and-time} segment (the directory right before fixed/path) date_time=$(echo "$file_path" | awk -F'/fixed/path/' '{print $1}' | xargs basename) # Extract the {filename} segment (the actual file name at the end of the path) filename=$(basename "$file_path") # Build the target directory path target_dir="$base_dir/$filename/$date_time" # Create the target directory (recursively, so parent folders are auto-created) mkdir -p "$target_dir" # Move the file to its new location mv "$file_path" "$target_dir" # Optional: Print progress to track what's being processed echo "Moved: $file_path → $target_dir/$filename" done
Step 3: Safety & Usage Tips
- Test First: Before running the actual move, replace
mv "$file_path" "$target_dir"withecho mv "$file_path" "$target_dir"to preview all operations. This lets you verify paths are correct without modifying any files. - Handle Special Characters: The script uses double quotes around all variables, so it works seamlessly with filenames/date-time strings containing spaces, hyphens, or other special characters.
- Permission Check: Ensure you have read access to the source files and write access to the parent directory where you’re creating new
{filename}folders. - Resumable: If the script gets interrupted mid-run, just re-run it—it will only process files still in their original source paths.
Step 4: Execute the Script
- Make the script executable:
chmod +x move_files.sh - Run it:
./move_files.sh
That’s all! This script will efficiently swap the date-time and filename segments in your file paths for all 1000+ files.
内容的提问来源于stack exchange,提问作者Charles
相关产品推荐
相关产品推荐

