我正在尝试匹配固定的模式/字符串:
print
int
在此示例中,使用grep -F 'int'
orgrep -F "int"
通常会得到带有 -F 标志的“固定”字符串...
int
但它匹配本示例中的两个字符串(而不是仅匹配带有without 的行print
)。
虽然似乎许多其他帖子都有类似的目标/问题,这里清楚地表明,在所述帖子上推荐的 -F 标志不起作用。
如何使用 grep 匹配实际的固定字符串?
答案1
-F
只是关闭对像.
和等字符*
作为正则表达式元字符的解释,而是将它们视为字符串文字。它对模式是否匹配子字符串、整个单词或整行没有影响 - 为此您需要-w
或-x
标志:
-w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $.
答案2
问题是“int”也出现在“print”一词的末尾。
使用 -F 固定字符串可能只是禁用正则表达式搜索,但固定字符串“int”仍然在单词“print”中。
解决方案可能是返回使用正则表达式,并指定您还需要单词边界来进行“整个单词”搜索
echo -e 'int\nprint' | grep '\bint\b'
答案3
尝试以下之一:
echo -e 'int\nprint\print' |grep -P '(^|\s)\int(?=\s|$)'
echo 'int - print'|grep -E '(^|\s)int($|\s)'
echo 'int - print'|grep -Fw "int"