Ben
Ben

Reputation: 6907

Grep for literal strings

I'm after a grep-type tool to search for purely literal strings. I'm looking for the occurrence of a line of a log file, as part of a line in a seperate log file. The search text can contain all sorts of regex special characters, e.g., []().*^$-\.

Is there a Unix search utility which would not use regex, but just search for literal occurrences of a string?

Upvotes: 144

Views: 74236

Answers (6)

anapsix
anapsix

Reputation: 2095

I really like the -P flag available in GNU grep for selective ignoring of special characters.

It makes grep -P "^some_prefix\Q[literal]\E$" possible

from grep manual

-P, --perl-regexp Interpret I as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features.

Upvotes: 3

parandhaman
parandhaman

Reputation: 31

cat list.txt
one:hello:world
two:2:nothello

three:3:kudos

grep --color=always -F"hello

three" list.txt

output

one:hello:world
three:3:kudos

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342799

you can also use awk, as it has the ability to find fixed string, as well as programming capabilities, eg only

awk '{for(i=1;i<=NF;i++) if($i == "mystring") {print "do data manipulation here"} }' file

Upvotes: 3

paxdiablo
paxdiablo

Reputation: 882196

That's either fgrep or grep -F which will not do regular expressions. fgrep is identical to grep -F but I prefer to not have to worry about the arguments, being intrinsically lazy :-)

grep   ->  grep
fgrep  ->  grep -F  (fixed)
egrep  ->  grep -E  (extended)
rgrep  ->  grep -r  (recursive, on platforms that support it).

Upvotes: 20

Scott Stafford
Scott Stafford

Reputation: 44808

You can use grep for that, with the -F option.

-F, --fixed-strings       PATTERN is a set of newline-separated fixed strings

Upvotes: 186

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799180

Pass -F to grep.

Upvotes: 4

Related Questions