【问题标题】:Get all the lines with a certain string获取具有特定字符串的所有行
【发布时间】:2015-10-25 01:50:48
【问题描述】:

我有一个小问题,希望有人能帮我解决这个问题。基本上,我有一个从 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

谢谢!

【问题讨论】:

    标签: string bash shell grep find


    【解决方案1】:

    这是一个如何使用 sed 完成此操作的示例,在我刚刚在 jsfiddle 上创建的页面上进行了测试:

    curl --silent http://jsfiddle.net/udfmq9jv/| grep -F '/watch?v='| sed -E 's!.*/watch\?v=([a-zA-Z0-9_-]*).*!\1!';
    ## 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_-]*).*!\1!');
    echo ${#ids[@]};
    ## 3
    echo "${ids[0]}";
    ## a1Y73sPHKxw
    echo "${ids[1]}";
    ## -rIEVBIP5yc
    echo "${ids[2]}";
    ## dMH0bHeiRNg
    

    【讨论】:

    • 好的,但是两次输出相同的id,这正常吗?另外,如果我要使用该数据,我将如何获取它并将其放入变量中,也许是数组或其他东西?
    • 关于两次输出相同的id,如果源中存在相同的id,就会发生这种情况。您可以...| sort| uniq 删除重复项。
    • 好吧,我想我知道为什么它把 id 放了两次,因为当你点击链接和缩略图时都有一个 href。因此,我将尝试寻找一种删除重复项的方法。所以要放入一个变量,我应该这样做variable=$(curl --silent http://jsfiddle.net/udfmq9jv/| grep -F '/watch?v='| sed -E 's!.*/watch\?v=([a-zA-Z0-9_-]*).*!\1!';)
    • 使用以下语法:for ((i = 0; i &lt; ${#ids[@]}; ++i)); do stmt1; stmt2; ...; done;.
    猜你喜欢
    • 2012-06-05
    • 2019-04-22
    • 2021-07-12
    • 1970-01-01
    • 2022-01-08
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多