检查变量是否包含特定的文本字符串 bash

Check if variable contains specific text string bash

我想检查 $url 的内容是否在 https://youtube.com/watch? 之后的任何地方包含 v=

示例输出(记下 v= 的现有实例和缺失实例):

> https://youtube.com/watch?list=PL3O9DAQHAxSTXqOH5VV6DO0BBupZ4feqz&v=apdJBcDF6vA&index=2
URL allowed.

> https://youtube.com/watch?list=PL3O9DAQHAxSTXqOH5VV6DO0BBupZ4feqz&index=2
URL NOT allowed.

> https://youtube.com/watch?v=apdJBcDF6vA
URL allowed.

> https://youtube.com/v=apdJBcDF6vA
URL NOT allowed.

> https://youtube.com/watch?v=apdJBcDF6vA&list=PL3O9DAQHAxSTXqOH5VV6DO0BBupZ4feqz&index=2
URL allowed.

> https://youtube.com/watch?v=apdJBcDF6vA&list=PL3O9DAQHAxSTXqOH5VV6DO0BBupZ4feqz
URL allowed.

> https://youv=tube.com/watch?v=apdJBcDF6vA
URL NOT allowed.

> v=https://youtube.com/watch?v=apdJBcDF6vA
URL NOT allowed.

我会尝试一些代码来测试,但老实说我不确定该用什么。

OS 是 macOS High Sierra 10.13.6 和 bash 版本是 3.2.57(1)-release

在双方括号内,== 运算符支持 glob:

if [[ $url == 'https://youtube.com/watch?'*v=* ]]

如果你想要获取视频ID,用正则表达式就可以很简单的实现。请参阅 How do I get the YouTube video ID from a URL? 或尝试使用谷歌搜索 'regex to get youtube video id'

如果您不知道,请考虑使用 youtube-dl 的部分内容,它们可以解析所有可能的东西 url 并且有更多的工具可以做很多事情。