如何捕获bash脚本的输出并将其导入到另一个?
在我的Arch Linux PC上,我从官方存储库下载了包youtube-dl
。当我用它来下载YouTube视频的MP4格式,结果看起来是这样的(我将使用“$”来表示shell提示符):如何捕获bash脚本的输出并将其导入到另一个?
`$ youtube-dl --format mp4 https://www.examplelink.com`
[youtube] Q0CbN8sfihY: Downloading webpage
[youtube] Q0CbN8sfihY: Downloading video info webpage
[youtube] Q0CbN8sfihY: Extracting video information
[youtube] Q0CbN8sfihY: Downloading MPD manifest
[download] Destination: ExampleVideo.mp4
[download] 100% of 15.07MiB in 00:20`
,我希望能赶上从视频标题该输出,并且将其导入到另一个脚本,它看起来像这样:
`#! /bin/bash`
`track=`echo "[email protected]"`
music='/home/samuel/Music/'
video='/home/samuel/Videos/'
ffmpeg -i "$video$track".mp4 -acodec libmp3lame -ab 160k -ar 44100 -ac 2 "$music$track".mp3`
这将.mp4
文件转换为.mp3
格式,反过来,创建一个完全自动化的过程。你会如何捕捉视频标题的名称并将其导入到其他脚本中?
你只是问如何捕获下载的文件的名称?输出只是标准输出吗?假设你的脚本名称为nameIt
,试试这个 -
youtube-dl --format mp4 https://www.examplelink.com 2>&1 |
tee whole.log | # save the whole log just in case
grep Destination: | # pass only the relevant line through
{ read x x file; nameIt $file }
大多数人会说用awk - 我让他们提供的方式来做到这一点。 围绕读取/回显的{ ... }
是因为read
将var作用于流水线。您可以将其传递给其他脚本,而不是回显。
你也可以更换{ ... }
与sed 's/.* //'
,它管直接到您的其他脚本,正好赶上它的标准输入,而不是期待它为$ 1,这将是这样的:
youtube-dl --format mp4 https://www.examplelink.com 2>&1 |
tee whole.log | # save the whole log just in case
grep Destination: | # pass only the relevant line through
s/.* //' | # spit out the filename
nameIt # prog reads stdin
在这种情况下,你的代码代替,
`track=`echo "[email protected]"`
只想说,像
read track
有很多方法可以做到这一点。
你可以尝试像: 第一行设置你的变量,再后来我重命名和移动文件,删除空格,甚至(可应用到其他caracters太)
filename=$(youtube-dl --format mp4 https://www.youtube.com/watch?v=VgbnndezHbw|grep Destination|cut -f2 -d:) echo "$filename" newfilename="$(echo "$filename"|sed "s/^[ \t]*//"|tr ' ' '_')" mv "$(echo "$filename"|sed 's/^ *//')" "$newfilename" echo "$newfilename"
的更好的方式来做到这一点:
youtube-dl --exec 'echo "file: {}"' <<URL>>
我这里使用的只是一个回波作为一个例子,但你可以下载后打电话给你想要的任何功能,并与大括号它传递的文件名。就像find命令一样。