3

Perl has a function called metaquote() to escape all special characters for a regular expression.

Is there an equivalent technique for egrep?

Example: If I am searching for the string abc.def.ghi, I need to remember to escape the dots manually, e.g., abc\.def\.ghi

I assume egrep does not have a built-in mode/feature to do this, but I am open to "one-liners" in Perl/sed/awk to simulate metaquote() for egrep. Also, Perl's metaquote() might work in trivial cases, but the regular expression syntax is different between egrep and perl.

2 Answers 2

4

Use the -F options to make grep treat pattern as fixed string:

grep -F 'abc.def.ghi' <file

And also note that you don't need to invoke egrep.

4
  • Re: "you don't need to invoke egrep": As I understand, GNU egrep is little more than grep -E for extended regex. I realise in my example above, the regex is trivial, but normally they are a bit more complex, so I use egrep. Is egrep useless then?
    – kevinarpe
    Nov 19, 2015 at 5:54
  • 1
    @kevinarpe: egrep is the same as grep -E.
    – cuonglm
    Nov 19, 2015 at 6:38
  • I want to clarify for this answer. Option -F will not work with egrep; it only works with grep. When I use egrep -F, I receive the error egrep: egrep can only use the egrep pattern syntax.
    – kevinarpe
    Nov 19, 2015 at 7:44
  • 1
    @kevinarpe: Yes, because using -F meaning you search for fixed-string, which is not consider a regex, so you have a conflict matcher. Try grep -EF '123' <<<"" to see the error.
    – cuonglm
    Nov 19, 2015 at 7:48
2

You do have to do it yourself: this sed command escaped any non-alphanumeric character, which is what quotemeta does (IIRC)

str="abc.def.ghi"
escaped=$(sed 's/[^[:alnum:]]/\\&/g' <<< "$str")

echo "$escaped"    # => abc\.def\.ghi
  1. we expect this to match because it's using the original string as a regular expression

    $ echo "foo bar abc-def-ghi baz" | grep "$str"
    foo bar abc-def-ghi baz
    
  2. we expect this not to match because it's using the escaped string.

    $ echo "foo bar abc-def-ghi baz" | grep "$escaped"
    $ echo $?
    1
    
  3. we expect this to match because it's using the escaped string.

    $ echo "foo bar abc.def.ghi baz" | grep "$escaped"
    foo bar abc.def.ghi baz
    

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .