这个问题的解决方法可以分为两步。第一步编写一个脚本来创建文件夹,第二步编写一个脚本来遍历文件夹中的所有文件并将它们移动和重命名到相应的文件夹中。
以下是完整的解决方案,包括两个脚本:
#!/bin/bash
#
# This script creates directories based on the file name and moves files into
# their corresponding directories.
# Check if a directory name is provided as a command-line argument
if [ $# -ne 1 ]
then
echo "Usage: $(basename $0) " >&2
exit 1
fi
# Set the directory path and ensure that it exists
dir=$1
if [ ! -d "$dir" ]
then
echo "Error: $dir does not exist or is not a directory!" >&2
exit 1
fi
# Loop through each file in the current directory
for file in *
do
# Check if the file is a regular file
if [ -f "$file" ]
then
# Extract the file name without the extension
filename=$(basename "$file")
filename="${filename%.*}"
# Create a directory with the same name as the file, if it does not exist
if [ ! -d "$dir/$filename" ]
then
echo "Creating directory: $dir/$filename"
mkdir "$dir/$filename"
fi
# Move the file into the corresponding directory and add a suffix
suffix=1
while [ -e "$dir/$filename/$filename-$suffix.${file##*.}" ]
do
((++suffix))
done
echo "Moving file: $file to $dir/$filename/$filename-$suffix.${file##*.}"
mv "$file" "$dir/$filename/$filename-$suffix.${file##*.}"
fi
done
在这个脚本中,我们首先检查用户是否提供了