歌单生成脚本代码
#!/bin/bash
# 获取当前目录的绝对路径(解决符号链接问题)
current_dir=$(pwd -P)
# 遍历当前目录下的所有子文件夹
for dir in */; do
# 去除路径末尾的斜杠
dir_name="${dir%/}"
# 设置歌单名称(子文件夹名.m3u)
playlist_name="${dir_name}.m3u"
# 删除已存在的旧歌单
rm -f "$playlist_name"
# 查找该子目录下的音频文件(包含子目录)
find "${current_dir}/${dir_name}" -type f \( \
-iname "*.mp3" -o \
-iname "*.flac" -o \
-iname "*.wav" -o \
-iname "*.ogg" -o \
-iname "*.m4a" -o \
-iname "*.aac" -o \
-iname "*.wma" \) \
| sort --ignore-case \
>> "$playlist_name"
# 转换路径为UNIX格式(可选,解决Windows兼容问题)
sed -i 's/\\/\//g' "$playlist_name"
# 统计歌曲数量
song_count=$(wc -l < "$playlist_name" 2>/dev/null)
# 输出结果
if [ "$song_count" -gt 0 ]; then
echo "✅ 已生成歌单: ${playlist_name} (${song_count}首)"
echo " 示例路径: $(head -1 "$playlist_name")"
else
rm -f "$playlist_name"
echo "⚠️ 跳过空文件夹: ${dir_name}"
fi
done
echo "🎉 所有歌单生成完成!"
假设目录结构为:
MyMusic/
**── Artist_A/
** **── song1.mp3
** **── song2.flac
**── Artist_B/
** **── album.mp3
**── EmptyFolder/
将生成:
Artist_A.m3u
Artist_B.m3u
特点:
- 每个子文件夹生成独立歌单
- 不包含子文件夹的子目录内容(
-maxdepth 1
)
- 自动跳过空文件夹
- 显示每个歌单的歌曲数量
- 保留文件夹层级关系(例如
Artist_A/song1.mp3
)
如果需要包含子文件夹的子目录内容(即递归搜索),只需删除 -maxdepth 1
参数即可。