【问题标题】:I can't figure out how to extract a string in bash我不知道如何在 bash 中提取字符串
【发布时间】:2016-10-04 06:05:49
【问题描述】:

我正在尝试制作一个 bash 脚本,该脚本将下载一个 youtube 页面,查看最新视频并找到它的 url。我有下载页面的部分,除了我不知道如何用 url 隔离文本。 我有这个下载页面

curl -s https://www.youtube.com/user/h3h3Productions/videos > YoutubePage.txt

这会将其保存到文件中。 但我无法弄清楚如何隔离 div 的单个部分。 div是

<a class="yt-uix-sessionlink yt-uix-tile-link  spf-link  yt-ui-ellipsis yt-ui-ellipsis-2" dir="ltr" title="Why I'm Unlisting the Leafyishere Rant" aria-describedby="description-id-877692" data-sessionlink="ei=a2lSV9zEI9PJ-wODjKuICg&amp;feature=c4-videos-u&amp;ved=CD4QvxsiEwicpteI1I3NAhXT5H4KHQPGCqEomxw" href="/watch?v=q6TNODqcHWA">Why I'm Unlisting the Leafyishere Rant</a>

我需要在最后隔离 href 但我不知道如何使用 grep 或 sed 来做到这一点。

【问题讨论】:

  • edit 您的问题包括将产生该输出的示例输入 (The div is)。套用空手道小子 3 的话说,“一个人看不见,他无法解析”。

标签: bash sed grep find cut


【解决方案1】:

使用 sed :

sed -n 's/<a [^>]*>/\n&/g;s/.*<a.*href="\([^"]*\)".*/\1/p'  YoutubePage.txt

只提取视频ahref

$ sed -n 's/<a [^>]*>/\n&/g;s/.*<a.*href="\(\/watch\?[^"]*\)".*/\1/p' YoutubePage.txt
/watch?v=q6TNODqcHWA
/watch?v=q6TNODqcHWA
/watch?v=ix4mTekl3MM
/watch?v=ix4mTekl3MM
/watch?v=fEGVOysbC8w
/watch?v=fEGVOysbC8w
...

省略重复的行:

$ sed -n 's/<a [^>]*>/\n&/g;s/.*<a.*href="\(\/watch\?[^"]*\)".*/\1/p' YoutubePage.txt | sort | uniq
/watch?v=2QOx7vmjV2E
/watch?v=4UNLhoePqqQ
/watch?v=5IoTGVeqwjw
/watch?v=8qwxYaZhUGA
/watch?v=AemSBOsfhc0
/watch?v=CrKkjXMYFzs
...

您也可以将其通过管道传递给您的 curl 命令:

curl -s https://www.youtube.com/user/h3h3Productions/videos | sed -n 's/<a [^>]*>/\n&/g;s/.*<a.*href="\(\/watch\?[^"]*\)".*/\1/p' | sort | uniq

【讨论】:

    【解决方案2】:

    您可以使用lynx,它是一个终端浏览器,但有一个-dump 模式,它将输出HTML 解析文本,并提取URL。这使得 grep 网址更容易:

    lynx -dump 'https://www.youtube.com/user/h3h3Productions/videos' \
      | sed -n '/\/watch?/s/^ *[0-9]*\. *//p'
    

    这将输出如下内容:

    https://www.youtube.com/watch?v=EBbLPnQ-CEw
    https://www.youtube.com/watch?v=2QOx7vmjV2E
    ...
    

    细分:

    -n '                             # Disable auto printing
        /\/watch?/                   # Match lines with /watch?
                  s/^ *[0-9]*\. *//  # Remove leading index: " 123. https://..." -> 
                                     # "https://..."
                                   p # Print line if all the above have not failed.
                                    '
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-31
      • 2022-10-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多