在这里,我为您翻译的部分是:”grep for full raw multi-line string”。

huangapple go评论63阅读模式
英文:

grep for full raw multi-line string

问题

以下是您要翻译的代码部分:

$ echo ''
  - key: val
    baz: foo
'' | grep -F "$(
cat <<EOM
  - key: val
    foo: baz
EOM
)"

输出是部分匹配

  - key: val

但如果完全找到给定的heredoc字符串,我想什么都不得到。

是否可以使用grep来查找完整的原始多行字符串(而不是正则表达式)?如果可以,那么应该如何执行?

英文:

This the following

$ echo &#39;
  - key: val
    baz: foo
&#39; | grep -F &quot;$(
cat &lt;&lt;EOM
  - key: val
    foo: baz
EOM
)&quot;

The output is a partial match

  - key: val

but I would like to get nothing if the whole given heredoc string is fully found and nothing otherwise.

Is it possible to grep for full raw multi-line string (not a regular expression)? If so, then how should it be done?

答案1

得分: 1

以下是您要翻译的内容:

首先,要在grep中获得精确匹配,您需要使用-x选项。

然而,正如我最初怀疑的那样,即使是完全匹配,grep -x也会由于存在换行符而失败。

一个技巧是使用tr从原始和模式字符串中去除所有换行符,并像这样使用-x

echo &#39;
  - key: val
    baz: foo
&#39; | tr -d &#39;\n&#39; | grep -q -xF -- &quot;$(
cat &lt;&lt;EOM | tr -d &#39;\n&#39;
  - key: val
    foo: baz
EOM
)&quot; &amp;&amp; echo &quot;match&quot; || echo &quot;nope&quot;


echo &#39;
  - key: val
    baz: foo
&#39; | tr -d &#39;\n&#39; | grep -q -xF -- &quot;$(
cat &lt;&lt;EOM | tr -d &#39;\n&#39;
  - key: val
    baz: foo
EOM
)&quot; &amp;&amp; echo &quot;match&quot; || echo &quot;nope&quot;

输出:

nope
match

请注意使用-q来抑制grep的正常输出,并仅使用退出代码。还使用了--来分隔选项和模式。

英文:

First thing is that to get exact match in grep you will need to use -x option.

However, as I suspected initially grep -x will fail for even the full match due to presence of line breaks.

One trick is to use tr to strip all line breaks from original and pattern strings and use -x like this:

echo &#39;
  - key: val
    baz: foo
&#39; | tr -d &#39;\n&#39; | grep -q -xF -- &quot;$(
cat &lt;&lt;EOM | tr -d &#39;\n&#39;
  - key: val
    foo: baz
EOM
)&quot; &amp;&amp; echo &quot;match&quot; || echo &quot;nope&quot;


echo &#39;
  - key: val
    baz: foo
&#39; | tr -d &#39;\n&#39; | grep -q -xF -- &quot;$(
cat &lt;&lt;EOM | tr -d &#39;\n&#39;
  - key: val
    baz: foo
EOM
)&quot; &amp;&amp; echo &quot;match&quot; || echo &quot;nope&quot;

Output:

nope
match

Note use of -q to suppress normal output of grep and use only the exit code. Also used -- to separate options from pattern.

huangapple
  • 本文由 发表于 2023年6月29日 23:23:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定