You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在youtube-dl中提取视频标题数字并做减法实现自定义命名

实现方案

youtube-dl 本身的输出文件名模板不支持正则提取和数学运算,需要配合 --exec 参数调用 shell 命令完成自定义重命名逻辑,以下是两种可直接用的方案:

方案1:直接改造原有命令

直接在原命令基础上增加 --exec 逻辑,无需额外文件:

cd /home/ahmed/Downloads && youtube-dl \
-f 'bestvideo[height<=1080]+bestaudio/best[height<=1080]' \
--merge-output-format mkv \
--playlist-reverse \
--playlist-end 1 \
--exec '
# 从标题提取第一个出现的数字(总集数)
total_ep=$(echo "%(title)s" | grep -oE "[0-9]+" | head -n1)
# 计算当前季集数
season_ep=$((total_ep - 27))
# 重命名为目标格式
mv {} "Kurulus Osman S02E${season_ep}.mkv"
' \
https://www.youtube.com/playlist?list=PLCuVYHE7O2A0XGkdhaU_M4-IkEIq5hSOQ

方案2:封装为独立脚本(更适合 cron 定时任务)

单独封装为shell脚本,可增加异常校验逻辑,避免定时任务运行出错:

  1. 新建脚本文件 download_osman.sh,写入以下内容:
#!/bin/bash
cd /home/ahmed/Downloads || exit 1

youtube-dl \
-f 'bestvideo[height<=1080]+bestaudio/best[height<=1080]' \
--merge-output-format mkv \
--playlist-reverse \
--playlist-end 1 \
--exec '
total_ep=$(echo "%(title)s" | grep -oE "[0-9]+" | head -n1)
# 校验提取的总集数合法性
if [[ $total_ep =~ ^[0-9]+$ && $total_ep -gt 27 ]]; then
    season_ep=$((total_ep - 27))
    mv {} "Kurulus Osman S02E${season_ep}.mkv"
else
    # 异常情况写入日志方便排查
    echo "[$(date)] 无法从标题提取有效总集数:%(title)s" >> /var/log/osman_download.log
fi
' \
https://www.youtube.com/playlist?list=PLCuVYHE7O2A0XGkdhaU_M4-IkEIq5hSOQ
  1. 给脚本添加执行权限:
chmod +x /path/to/download_osman.sh
  1. cron 定时任务中直接填写脚本的绝对路径即可。

调整说明

  • 后续更换下载季数时,只需修改代码中的减数(27为前一季总集数)和文件名中的季数标识(S02)即可
  • 如果标题结构变化导致数字提取错误,调整 grep 后的正则规则和 head/tail 参数即可匹配对应位置的数字

内容的提问来源于stack exchange,提问作者Ahmed Allangawi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 17:15:03