How to grep exact literal string (no regex)
25,461
Solution 1
Use fgrep
, it's the same as grep -F
(matches a fixed string).
Solution 2
Well, you can put the information you want to match, each in a line, and then use grep
:
grep -F -f patterns.txt file.txt
Notice the usage of the flag -F
, which causes grep
to consider each line of the file patterns.txt as a fixed-string
to be searched in file.txt.
Author by
Nathan J.B.
Updated on July 09, 2022Comments
-
Nathan J.B. almost 2 years
Is there a way to
grep
(or use another command) to find exact strings, using NO regex?For example, if I want to search for (literally):
/some/file"that/has'lots\of"invalid"chars/and.triggers$(#2)[*~.old][3].html
I don't want to go through and escape every single "escapable". Essentially, I want to pass it through, like I would with
echo
:$ echo "/some/file\"that/has'lots\of\"invalid\"chars/and.triggers$(#2)[*~.old][3].html" /some/file"that/has'lots\of"invalid"chars/and.triggers$(#2)[*~.old][3].html
-
Nathan J.B. almost 11 yearsWorked perfectly with
fgrep 'preg_replace("/([a-z]+)([A-Z])/"' . -R
(which failed withgrep
). You will still have to escape$
, but that's livable. -
Nathan J.B. almost 11 yearsIt's worth noting that this is the same as
fgrep -f patterns.txt file.txt
. By using a file of patterns,$
does not need to be escaped. I ultimately decided to accept the other because it's the least time consuming. -
Lily Finley over 9 years
grep -F
seems to be preferred now. "Direct invocation as either egrep or fgrep is deprecated" fgrep(1) - Linux man page