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

如何为Bash脚本中yt-dlp的指定输出内容添加着色?

为yt-dlp输出添加自定义着色

问题背景

我有一个Bash脚本用来下载Rumble频道最新2集视频,用yt-dlp的-w参数避免覆盖已存在文件。现在想给输出里的**"Destination"及其文件名**、"has already been downloaded"提示添加着色,方便查看。原脚本如下:

cd /tmp
EPI=$(curl -s https://rumble.com/c/robbraxman | grep  -m 2 "href=/\v"| awk '{print $5}' |awk -F\> '{print $1}')
for i in ${EPI//href=/http://rumble.com}; do
  printf "\e[1;38;5;212m Downloading \e[1;38;5;196m $i\e[m \n"
  yt-dlp -f mp4-480p -w $i
done

yt-dlp的输出示例:

[Rumble] Extracting URL: http://rumble.com/v2820uk-let-me-show-you-brax.me-privacy-focused-app.html
[Rumble] v2820uk-let-me-show-you-brax.me-privacy-focused-app.html: Downloading webpage
[RumbleEmbed] Extracting URL: https://rumble.com/embed/v25g3g0
[RumbleEmbed] v25g3g0: Downloading JSON metadata
[info] v25g3g0: Downloading 1 format(s): mp4-480p
[download] Let Me Show You Brax.Me - Privacy Focused App [v25g3g0].mp4 has already been downloaded
[download] 100% of   20.00MiB

[Rumble] Extracting URL: http://rumble.com/v2820uk-let-me-show-you-brax.me-privacy-focused-app.html
[Rumble] v2820uk-let-me-show-you-brax.me-privacy-focused-app.html: Downloading webpage
[RumbleEmbed] Extracting URL: https://rumble.com/embed/v25g3g0
[RumbleEmbed] v25g3g0: Downloading JSON metadata
[info] v25g3g0: Downloading 1 format(s): mp4-480p
[download] Destination: Let Me Show You Brax.Me - Privacy Focused App [v25g3g0].mp4
[download]   3.8% of  525.67MiB at    5.79MiB/s ETA 01:27^C

解决方案

通过管道将yt-dlp的输出传给sed,匹配目标行并添加ANSI颜色代码。修改后的脚本如下:

cd /tmp
EPI=$(curl -s https://rumble.com/c/robbraxman | grep  -m 2 "href=/\v"| awk '{print $5}' |awk -F\> '{print $1}')
for i in ${EPI//href=/http://rumble.com}; do
  printf "\e[1;38;5;212m Downloading \e[1;38;5;196m $i\e[m \n"
  # 处理yt-dlp输出,添加自定义着色
  yt-dlp -f mp4-480p -w "$i" 2>&1 | sed -E '
      # 给Destination行添加亮蓝色
      s/(\[download\] Destination: .*)/\x1b[1;34m\1\x1b[0m/;
      # 给已下载提示行添加亮绿色
      s/(\[download\] .* has already been downloaded)/\x1b[1;32m\1\x1b[0m/
  '
done

关键说明

  1. 2>&1:将yt-dlp的标准错误输出(大部分状态信息在此)重定向到标准输出,确保所有内容都能被sed处理
  2. sed -E:使用扩展正则表达式,简化复杂行的匹配逻辑
  3. 颜色代码说明:
    • \x1b[1;34m:亮蓝色,标记目标文件路径
    • \x1b[1;32m:亮绿色,标记已下载完成的提示
    • \x1b[0m:重置颜色,避免后续输出被持续着色
  4. $i用双引号包裹:防止URL中包含空格或特殊字符导致命令执行错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:25:22