Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regex OR in grep in Cygwin?

Tags:

regex

grep

cygwin

I need to return results for two different matches from a single file.

grep "string1" my.file 

correctly returns the single instance of string1 in my.file

grep "string2" my.file 

correctly returns the single instance of string2 in my.file

but

grep "string1|string2" my.file 

returns nothing

in regex test apps that syntax is correct, so why does it not work for grep in cygwin ?

like image 514
rob Avatar asked Oct 24 '11 11:10

rob


1 Answers

Using the | character without escaping it in a basic regular expression will only match the | literal. For instance, if you have a file with contents

string1 string2 string1|string2 

Using grep "string1|string2" my.file will only match the last line

$ grep "string1|string2" my.file string1|string2 

In order to use the alternation operator |, you could:

  1. Use a basic regular expression (just grep) and escape the | character in the regular expression

    grep "string1\|string2" my.file

  2. Use an extended regular expression with egrep or grep -E, as Julian already pointed out in his answer

    grep -E "string1|string2" my.file

  3. If it is two different patterns that you want to match, you could also specify them separately in -e options:

    grep -e "string1" -e "string2" my.file

You might find the following sections of the grep reference useful:

  • Basic vs Extended Regular Expressions
  • Matching Control, where it explains -e
like image 82
Xavi López Avatar answered Sep 29 '22 13:09

Xavi López