获取具有特定字符串的所有行
Get all the lines with a certain string
我有一个小问题,希望有人能帮助我。基本上,我有一个从 Youtube 下载缩略图的脚本,它工作正常,但现在我希望它更高级,并且可以选择提供播放列表的 url(系统选择已经制作)并获得播放列表的html页,然后找到所有包含/watch?v=(视频的url)的行,然后取出除视频id(v之后的一系列字符)之外的所有内容=).
现在我的下载系统可以正常工作了,但我就是找不到用 /watch?v= 获取行的方法。
这是我下载网页和查找行部分的代码
read -p "Enter the url of the playlist : " link #Ask for url
content=$(curl $link --silent) #Downloads the webpage
contentxt="$basedir/playlist_page.txt" #Creates a file to store the webpage
echo $content > "$contentxt" #Saves the webpage into the file
url=$(grep -F "/watch?v=" $contentxt) #Find a line with the /watch?v=
echo $url #Displays that line containing the url to be used later
谢谢!
这是一个如何使用 sed
完成此操作的示例,在我刚刚在 jsfiddle 上创建的页面上进行了测试:
curl --silent http://jsfiddle.net/udfmq9jv/| grep -F '/watch?v='| sed -E 's!.*/watch\?v=([a-zA-Z0-9_-]*).*!!';
## a1Y73sPHKxw
## -rIEVBIP5yc
## dMH0bHeiRNg
请注意,这里的正则表达式很重要:从 How to validate youtube video ids? 开始,视频 ID 中的有效字符是字母、数字、下划线和破折号。
有几种方法可以将命令的输出收集到变量中。下面是如何使用进程替换、while
循环和 read
:
来完成的
ids=(); while read -r; do ids+=("$REPLY"); done < <(curl --silent http://jsfiddle.net/udfmq9jv/| grep -F '/watch?v='| sed -E 's!.*/watch\?v=([a-zA-Z0-9_-]*).*!!');
echo ${#ids[@]};
## 3
echo "${ids[0]}";
## a1Y73sPHKxw
echo "${ids[1]}";
## -rIEVBIP5yc
echo "${ids[2]}";
## dMH0bHeiRNg
我有一个小问题,希望有人能帮助我。基本上,我有一个从 Youtube 下载缩略图的脚本,它工作正常,但现在我希望它更高级,并且可以选择提供播放列表的 url(系统选择已经制作)并获得播放列表的html页,然后找到所有包含/watch?v=(视频的url)的行,然后取出除视频id(v之后的一系列字符)之外的所有内容=).
现在我的下载系统可以正常工作了,但我就是找不到用 /watch?v= 获取行的方法。
这是我下载网页和查找行部分的代码
read -p "Enter the url of the playlist : " link #Ask for url
content=$(curl $link --silent) #Downloads the webpage
contentxt="$basedir/playlist_page.txt" #Creates a file to store the webpage
echo $content > "$contentxt" #Saves the webpage into the file
url=$(grep -F "/watch?v=" $contentxt) #Find a line with the /watch?v=
echo $url #Displays that line containing the url to be used later
谢谢!
这是一个如何使用 sed
完成此操作的示例,在我刚刚在 jsfiddle 上创建的页面上进行了测试:
curl --silent http://jsfiddle.net/udfmq9jv/| grep -F '/watch?v='| sed -E 's!.*/watch\?v=([a-zA-Z0-9_-]*).*!!';
## a1Y73sPHKxw
## -rIEVBIP5yc
## dMH0bHeiRNg
请注意,这里的正则表达式很重要:从 How to validate youtube video ids? 开始,视频 ID 中的有效字符是字母、数字、下划线和破折号。
有几种方法可以将命令的输出收集到变量中。下面是如何使用进程替换、while
循环和 read
:
ids=(); while read -r; do ids+=("$REPLY"); done < <(curl --silent http://jsfiddle.net/udfmq9jv/| grep -F '/watch?v='| sed -E 's!.*/watch\?v=([a-zA-Z0-9_-]*).*!!');
echo ${#ids[@]};
## 3
echo "${ids[0]}";
## a1Y73sPHKxw
echo "${ids[1]}";
## -rIEVBIP5yc
echo "${ids[2]}";
## dMH0bHeiRNg