我有一个文件夹结构如下
Main
├ Folder A
⏐ ├YYMMDD-Filename A
⏐ ├YYMMDD-Filename B
⏐ ...
├ Folder B
⏐ ├YYMMDD-Filename C
⏐ ├YYMMDD-Filename D
⏐ ├YYMMDD-Filename E
⏐ ...
├ Folder C
⏐ ├YYMMDD-Filename F
⏐ ├YYMMDD-Filename G
⏐ ...
...
我想编写一个 shell 脚本来“复制和移动”,然后删除此结构中以特定 YY(年份)开头的所有文件,例如(19,20,21) 从此文件夹结构移至首次执行时为空的目标文件夹。如果尚不存在,脚本应重新创建源中的子文件夹(文件夹 A、文件夹 B,...),然后将文件移动到其特定的目标子文件夹中。 删除操作应首先删除所选文件,如果文件删除后源文件夹为空,则还应删除源文件夹。
脚本参数:
我目前不知道如何做到这一点,因此非常感谢 shell 脚本老手的任何帮助。
我最近从事类似的工作,我必须管理复杂的文件夹结构并根据文件名自动执行文件操作。下面是一个可以帮助您完成相同任务的脚本。该脚本将允许您根据指定的年份前缀从源目录复制或移动文件(并在需要时删除它们)到目标目录。如果操作后源文件夹变空,它将在目标中重新创建文件夹结构并删除源文件夹。
脚本:
#!/bin/bash
# Function to recreate the folder structure in the destination
recreate_structure() {
local source="$1"
local destination="$2"
# Loop through each folder in the source directory
for folder in "$source"/*; do
if [ -d "$folder" ]; then
local folder_name=$(basename "$folder")
local folder_path="$destination/$folder_name"
# Create the folder structure in the destination directory
mkdir -p "$folder_path"
fi
done
}
# Function to move/copy files and delete folders if requested
process_files() {
local source="$1"
local destination="$2"
local year="$3"
local method="$4"
# Loop through each folder in the source directory
for folder in "$source"/*; do
if [ -d "$folder" ]; then
local folder_name=$(basename "$folder")
local folder_path="$destination/$folder_name"
# Move or copy files that start with the specified year
for file in "$folder"/${year}*; do
if [ -f "$file" ]; then
if [ "$method" == "copy" ]; then
cp "$file" "$folder_path"
elif [ "$method" == "purge" ]; then
mv "$file" "$folder_path"
fi
fi
done
# If purge is selected, delete the folder if it is empty
if [ "$method" == "purge" ]; then
rmdir "$folder" 2>/dev/null
fi
fi
done
}
# Check if the correct number of arguments is provided
if [ "$#" -lt 4 ]; then
echo "Usage: $0 <Source Path> <Destination Path> <Method: copy/purge> <Year(s)>"
exit 1
fi
# Assign arguments to variables
SOURCE_PATH="$1"
DESTINATION_PATH="$2"
METHOD="$3"
YEAR="$4"
# Validate the method argument
if [ "$METHOD" != "copy" ] && [ "$METHOD" != "purge" ]; then
echo "Error: Method must be either 'copy' or 'purge'."
exit 1
fi
# Recreate folder structure in the destination
recreate_structure "$SOURCE_PATH" "$DESTINATION_PATH"
# Process files by copying or moving, and deleting if necessary
process_files "$SOURCE_PATH" "$DESTINATION_PATH" "$YEAR" "$METHOD"
echo "Script executed successfully."
说明:
./your_script_name.sh /home/user/Main /home/user/Destination purge 20
如果您只想复制文件而不删除任何内容:
./your_script_name.sh /home/user/Main /home/user/Destination copy 20
这个脚本应该可以有效地处理您的任务。如果您需要任何修改或遇到任何问题,请随时询问!