如何修改bash+Python脚本实现多目录全量m3u8文件合并
M3U8合并脚本修改方案
修改核心逻辑
- 替换原有同名文件匹配规则:固定读取第一个目录下的
all_streams.m3u8作为基础流列表,遍历第二个目录下所有后缀为.m3u8的文件合并 - 冗余清理规则:
- 全局仅保留1个
#EXTM3U头和最高版本的#EXT-X-VERSION头 - 自动去重完全相同的频道条目(相同频道信息+相同流地址仅保留1条)
- 过滤空行、非标准注释行、缺失信息的无效频道条目
- 全局仅保留1个
- 输出严格遵循HLS m3u8标准格式,兼容所有主流播放器
修改后完整代码
Python处理脚本(保存为merge_m3u8.py)
import os import sys def clean_m3u8_content(file_path): entries = [] extinf_temp = None version = 1 if not os.path.exists(file_path): return entries, version with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: lines = f.readlines() for line in lines: line = line.strip() if not line: continue if line.startswith('#EXT-X-VERSION:'): try: current_v = int(line.split(':')[1]) if current_v > version: version = current_v except: pass continue if line == '#EXTM3U': continue if line.startswith('#EXTINF:'): extinf_temp = line continue if extinf_temp and not line.startswith('#'): entries.append((extinf_temp, line)) extinf_temp = None return entries, version def merge_m3u8(base_dir, merge_dir, output_path): base_file = os.path.join(base_dir, 'all_streams.m3u8') base_entries, max_version = clean_m3u8_content(base_file) all_entries = set(base_entries) for filename in os.listdir(merge_dir): if filename.lower().endswith('.m3u8'): merge_file = os.path.join(merge_dir, filename) merge_entries, file_version = clean_m3u8_content(merge_file) all_entries.update(merge_entries) if file_version > max_version: max_version = file_version with open(output_path, 'w', encoding='utf-8') as f: f.write('#EXTM3U\n') f.write(f'#EXT-X-VERSION:{max_version}\n\n') for extinf, url in all_entries: f.write(f'{extinf}\n{url}\n\n') print(f'合并完成,共{len(all_entries)}个有效频道,输出路径:{output_path}') if __name__ == '__main__': if len(sys.argv) != 4: print('用法:python merge_m3u8.py <第一个目录路径> <第二个目录路径> <输出文件路径>') sys.exit(1) merge_m3u8(sys.argv[1], sys.argv[2], sys.argv[3])
Bash调用脚本(保存为merge.sh)
#!/bin/bash if [ $# -ne 3 ];then echo "用法:$0 <存放all_streams.m3u8的目录> <存放其他m3u8的目录> <输出文件路径>" exit 1 fi BASE_DIR="$1" MERGE_DIR="$2" OUTPUT_FILE="$3" if [ ! -f "${BASE_DIR}/all_streams.m3u8" ];then echo "错误:${BASE_DIR}目录下不存在all_streams.m3u8" exit 1 fi python3 merge_m3u8.py "$BASE_DIR" "$MERGE_DIR" "$OUTPUT_FILE"
使用方法
- 给bash脚本赋予执行权限:
chmod +x merge.sh - 执行命令:
./merge.sh <存放all_streams.m3u8的目录路径> <存放其他m3u8的目录路径> <合并后输出文件路径> - 执行完成后即可在指定路径拿到可用的合并后m3u8文件
内容的提问来源于stack exchange,提问作者Bitsbb01
相关产品推荐
相关产品推荐

