Bash 正则表达式匹配不完全匹配

Bash regex match not matching exactly

我有一个要循环的文本行列表,以查找作为变量提供的特定术语。

假设在这种情况下,我正在寻找 my_search_term = "Ubuntu 2018".

我输入的文本行如下所示:

...所以我正在寻找可以跳过第一个字符串但在与第二个字符串匹配时回显并退出的东西。

for line in "${list_of_text_lines}"
do
    STR=$line
    SUB=$my_search_term
    if [[ "$STR" =~ .*"$SUB".* ]]; then
        echo $line
        exit
    fi
done

... 但我没有回显“Ubuntu 2018”,而是得到“Ubuntu 20.04LTS”。为什么?

非常感谢您的帮助,在此先感谢您!

编辑 1: 根据@Barmar 的建议,我删除了输入字段周围的引号,如下所示:

for line in ${list_of_text_lines}
do
    echo ${line}
    STR=$line
    SUB=$my_search_term
    if [[ "$STR" =~ .*"$SUB".* ]]; then
        echo $line
        exit
    fi
done

但这会循环遍历整个文本字符串而不进行匹配,我的 echo 语句输出如下:

...
"Ubuntu
2018"
"Ubuntu
20.04LTS"
...

在不存储命令输出的情况下,您可以像这样处理输入并进行匹配:

search_term='Ubuntu 2018'

while IFS= read -r line; do
   if [[ $line =~ $search_term ]]; then
      echo "matched: $line"
      exit
   fi
done < <(VBoxManage list vms)

PS:请注意,您的搜索词不是正则表达式,它只是一个固定的字符串。在这种情况下,您可以避免正则表达式并像这样进行全局比较:

while IFS= read -r line; do
   if [[ $line == $search_term ]]; then
      echo "matched: $line"
      exit
   fi
done < <(VBoxManage list vms)

编辑: OP 的确切工作代码是:

while IFS= read -r line; do
        STR=$line
        SUB=$specific_vm_cloned
        if [[ "$STR" = *"$SUB"* ]]; then
            echo $line
            exit
            fi
        fi
    done <<< "$(VBoxManage list vms)"