具有双引号和由单引号包围的变量替换的 Grep 模式

Nor*_*tfi 3 grep quoting variable-substitution pattern-matching

所以,假设我有以下模式:

Thisisatest="1"
Run Code Online (Sandbox Code Playgroud)

在一个名为file.

我想匹配上面的确切字符串,无论出于何种原因,我选择循环列表中的一些数字,将它们用作变量并尝试执行以下操作:

Thisisatest="$varhere"
Run Code Online (Sandbox Code Playgroud)

上面$varhere等于上面的数字,是1。(虽然我提到了循环数字,但这只是一个未来可能的用例,仍然是一个例子)

现在为了让事情变得更简单,假设我想使用上述变量及其内容匹配上述精确模式:

grep 'Thisisatest="$varhere"' file
Run Code Online (Sandbox Code Playgroud)

其中文件包含字符串Thisisatest="1"$varhere包含数字1

问题是,这行不通,因为在单引号之间(如上)不会发生变量扩展。

这是反击失败的尝试:

  1. 从变量替换替换内容
echo "${varhere/[0-9]*/Thisisatest=\"$varhere\"}"
Run Code Online (Sandbox Code Playgroud)

在这里我echo用来查看它是否输出正确的字符串,以便它可以用作 grep 的输入......它输出这个:

'Thisisatest="'1'"
Run Code Online (Sandbox Code Playgroud)
  1. 添加更多报价
echo "'Thisisatest="${varhere}"'"
Run Code Online (Sandbox Code Playgroud)

输出:

'Thisisatest='1''
Run Code Online (Sandbox Code Playgroud)
echo ''''Thisisatest=\"${varhere}\"''''
Run Code Online (Sandbox Code Playgroud)

输出:

Thisisatest="'1'"
Run Code Online (Sandbox Code Playgroud)

其余的很明显......现在上面的最后一次尝试似乎接近我想要的,但仍然不是。

有什么办法可以做到以上几点?