The -F
option or --fixed-string
, as you noted, disable the regexp engine and search for literal strings. It is useful to look for strings that are valid regular expressions, but would have a different meaning as such. E.g.:
grep -Fe '[warn]' app.log
The [warn]
pattern is a valid Basic Regular Expression (BRE
) and so without the -F
option grep
will search and catch any line with at least one of w
,a
, r
, or n
. (Note that the brackets are special in the shell too, so we need to quote them on the command line.)
As an example, assume we want to find the error messages from a log file like the following with lines like this (so, the lines with the [err]
tag):
[info] terrace lights on
[err] garage door control not responding
Using grep 'err'
would match both lines, as there's a hit in the word "terrace". grep '[err]'
would also match both lines, as both have an "e" (and an "r"). But here, grep -F '[err]'
would be a simple way to limit the match to the tags only. (Alternatively, one could use the default regex match and escape the brackets: grep -e '\[err\]'
, or grep -e '[[]err[]]'
or even grep '[[]err]'
. But that's uglier.)
If you have more patterns to search for, you can use the -e
option multiple times:
grep -F -e '[warn]' -e '[debug]' -e '[err]' app.log
Lines matching any of the patterns (at least one) will be matched.
The -x
, --line-regex
option can also be useful in this context as it means it only considers a line a match if the whole line matches the pattern. E.g. grep -x foo
will match if a line is foo
but not if the line is foobar
. And -Fx
together would only find exactly matching lines, whatever special characters they contain.
grep -F
can be invoked asfgrep
fgrep
is deprecated in favor ofgrep -F
.