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

