【问题标题】:How to determine if string is a substring to another string如何确定字符串是否是另一个字符串的子字符串
【发布时间】:2020-11-17 18:39:11
【问题描述】:

我正在尝试确定子字符串(文件名)是否存在于包含许多文件路径的大字符串中。这是我的代码,它不起作用(打印“不包含”)。我尝试与=~ 比较,不同的引号用法。似乎没有任何效果。您在我的代码中发现问题了吗?

#!/bin/bash

text="/path/to/some/file1-2-3.json /another/path/to/file4-5-6.json"
my_file="file1-2-3.json"

if [[ *"$my_file"* == "$text" ]]; then
    echo "Contain"
else
    echo "Does not contain"
fi

【问题讨论】:

    标签: string bash string-comparison


    【解决方案1】:

    如果你反转字符串,它会起作用:

    $ more script.sh
    #!/bin/bash
    
    text="/path/to/some/file1-2-3.json /another/path/to/file4-5-6.json"
    my_file="file1-2-3.json"
    
    if [[ "$text" == *"$my_file"* ]]; then
            echo "Contain"
    else
            echo "Does not contain"
    fi
    $ ./script.sh
    Contain
    $
    

    表格man bash:

    当使用 == 和 != 运算符时,运算符右侧的字符串为 被认为是一种模式,并根据下面模式匹配中描述的规则进行匹配...

    【讨论】:

    • 我刚刚发现我只是在写我自己的问题。多么令人不快的错误! :-D 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2019-05-11
    • 2011-02-07
    • 2021-10-26
    • 2013-09-06
    • 2011-06-15
    相关资源
    最近更新 更多