以下是一个简单的Bash脚本,可以将文件移动到以它们的文件名命名的目录中。该脚本将匹配以指定前缀开头的所有文件,并将它们移动到以该前缀命名的目录中。例如,如果有名为“file1”,“file2”,“file3”的文件,将它们移动到名为“file”目录中。
#!/bin/bash
# Set the directory containing the files to be moved
directory="/path/to/files"
# Get a list of all files in the directory
files=$(ls $directory)
# Loop through all the files
for file in $files
do
# Get the prefix of the file name
prefix=${file%%_*}
# Create a directory with the name of the prefix, if it doesn't already exist
if [ ! -d "$directory/$prefix" ]
then
mkdir "$directory/$prefix"
fi
# Move the file to the directory with the name of the prefix
mv "$directory/$file" "$directory/$prefix/$file"
done
使用此脚本时,请将文件路径“/path/to/files”替换为包含要移动的文件的目录的实际路径。运行脚本后,每个文件都将被移动到以其文件名前缀命名的目录中。例如,“file1”、“file2”、“file3”将被移动到“file”目录中。注意,文件名中使用下划线“_”分隔前缀和后缀。如果使用其他的分隔符,请将分隔符替换为上述脚本中相应的分隔符。