[!前言]
有时候会碰到这种情况,一个文件夹中存在大量文件,有些文件名称相同但是文件类型不同。如果想要将名称相同的文件保存至一个新建的文件夹中,这个文件夹以共同的名称命名,应该如何操作?

类似结构如图

image.png

目标是创建这是AAA,这是BBB,这是CCC文件夹并将相同名称的文件移动进去

创建脚本

如果是windows则新建一个文件并重新命名为merge_files.sh,如果是linux则nano merge_files.sh或者vim merge_files.sh

输入以下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/bin/bash

# 列出所有文件
list_files() {
local directory="$1"
find "$directory" -maxdepth 1 -type f
}

# 显示文件列表
display_files() {
local files=("$@")
echo "List of files:"
for file in "${files[@]}"; do
echo "$file"
done
}

# 合并文件
merge_files() {
local files=("$@")
declare -A file_dict
local errors=()

# 分类文件
for file in "${files[@]}"; do
base_name=$(basename "$file" | sed 's/\.[^.]*$//')
if [[ -z "${file_dict["$base_name"]}" ]]; then
file_dict["$base_name"]=""
fi
file_dict["$base_name"]+="$file;"
done

# 创建新文件夹并移动文件
for base_name in "${!file_dict[@]}"; do
IFS=';' read -r -a file_list <<< "${file_dict["$base_name"]}"
new_folder="$(dirname "${file_list[0]}")/$base_name"
mkdir -p "$new_folder"
for file in "${file_list[@]}"; do
mv "$file" "$new_folder" 2>/dev/null
if [ $? -ne 0 ]; then
errors+=("$file")
fi
done
echo "Files moved to $new_folder"
done

# 列出出错的文件
if [ ${#errors[@]} -gt 0 ]; then
echo "The following files could not be moved:"
for error in "${errors[@]}"; do
echo "$error"
done
else
echo "All files moved successfully."
fi
}

# 主函数
main() {
if [ $# -ne 1 ]; then
echo "Usage: $0 <directory-path>"
exit 1
fi

local directory="$1"

if [ ! -d "$directory" ]; then
echo "Error: Directory $directory does not exist."
exit 1
fi

mapfile -t files < <(list_files "$directory")
display_files "${files[@]}"

read -p "Do you want to merge files with the same name but different extensions? (Y/N): " choice
if [[ "$choice" == "Y" || "$choice" == "y" ]]; then
merge_files "${files[@]}"
else
echo "No files were merged."
fi
}

# 运行主函数
main "$@"


运行脚本

1
./merge_files.sh 需要合并的文件夹路径

image.png
不同的shell目录展示会有所不同,我这用的是cmder所以如上图展示,其他可能直接目录是E://test

执行以及结果输出

image.png