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
。
问题是,这行不通,因为在单引号之间(如上)不会发生变量扩展。
这是反击失败的尝试:
echo "${varhere/[0-9]*/Thisisatest=\"$varhere\"}"
Run Code Online (Sandbox Code Playgroud)
在这里我echo
用来查看它是否输出正确的字符串,以便它可以用作 grep 的输入......它输出这个:
'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)
echo ''''Thisisatest=\"${varhere}\"''''
Run Code Online (Sandbox Code Playgroud)
输出:
Thisisatest="'1'"
Run Code Online (Sandbox Code Playgroud)
其余的很明显......现在上面的最后一次尝试似乎接近我想要的,但仍然不是。
有什么办法可以做到以上几点?
grep "Thisisatest=\"${varhere}\""
Run Code Online (Sandbox Code Playgroud)
为我工作。“ \
”通过ONE shell解释翻转下一个字符的“我是一个特殊字符”标志。