如何用yt-dlp的Bash脚本从同一URL下载不同时段视频片段并解决跳过问题?
问题根源
你遇到的片段被跳过的核心原因是输出文件名重复:当前使用的输出模板%(id)s_%(title)s_%(duration)s.%(ext)s,对于同一个YouTube视频来说,视频ID、标题、总时长完全一致,所以第一个片段下载完成后,后续同视频的其他片段会被yt-dlp判定为已存在文件,直接跳过下载。
修复方案
1. 修改输出文件名模板
在输出模板中加入片段的起止时间,确保每个片段的文件名唯一。将输出参数修改为:
-o "%(id)s_%(title)s_${start_time_z//:/_}_${end_time_z//:/_}.%(ext)s"
这里用${start_time_z//:/_}把时间里的冒号替换成下划线,避免文件名包含特殊字符导致问题。
2. 修复脚本中的两处小错误
- 原脚本中
echo "Downloading: $url | Start Time: $start_time_z | End Time: $end_time_zc多了一个c,修正为$end_time_z - 原脚本中
if [ $missing ]的判断逻辑有问题,无论missing是true还是false都会触发警告,修正为if "$missing"
修改后的完整脚本
#!/bin/bash missing=false while IFS=, read -r url start_time_z end_time_z do if [ "$url" == "" ] then echo "url is empty or no value set" missing=true elif [ "$start_time_z" == "" ] then echo "Start Time is empty or no value set for URL: $url" missing=true elif [ "$end_time_z" == "" ] then echo "End Time is empty or no value set for URL: $url" missing=true else echo "Downloading: $url | Start Time: $start_time_z | End Time: $end_time_z" echo "-------------------------------------------------------------------------------------------------------------" yt-dlp -f "bestvideo[ext=mp4]+bestaudio[ext=m4a]" \ --download-sections "*$start_time_z-$end_time_z" --restrict-filenames \ -o "%(id)s_%(title)s_${start_time_z//:/_}_${end_time_z//:/_}.%(ext)s" "$url" \ --cookies /home/user1/yt-downloads/youtube_cookie.txt echo "-------------------------------------------------------------------------------------------------------------" fi done < "$1" if "$missing" then echo "WARNING: Missing values in a CSV file. Please use the proper format. Operation failed." exit 1 else echo "CSV file read successfully." fi
额外说明
- 如果你需要更简洁的文件名,也可以只加入起始时间或者自定义的片段编号(比如在CSV里加一列序号,脚本中读取后加入文件名)
--restrict-filenames参数已经会处理部分特殊字符,但替换时间里的冒号是必要的,因为多数文件系统不允许文件名包含冒号
内容的提问来源于stack exchange,提问作者Yashodhan K
相关产品推荐
相关产品推荐

