How to use regex OR in grep in Cygwin?

RegexCygwinGrep

Regex Problem Overview


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 ?

Regex Solutions


Solution 1 - Regex

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:

Solution 2 - Regex

You may need to either use egrep or grep -E. The pipe OR symbol is part of 'extended' grep and may not be supported by the basic Cygwin grep.

Also, you probably need to escape the pipe symbol.

Solution 3 - Regex

The best and most clear way I've found is: grep -e REG1 -e REG2 -e REG3 FILETOGREP

I never use pipe as it's less evident and very awkward to get working.

Solution 4 - Regex

You can find this information by reading the fine manual: grep(1), which you can find by running 'man grep'. It describes the difference between grep and egrep, and basic and regular expressions, along with a lot of other useful information about grep.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrobView Question on Stackoverflow
Solution 1 - RegexXavi LópezView Answer on Stackoverflow
Solution 2 - RegexJulianView Answer on Stackoverflow
Solution 3 - RegexTravisView Answer on Stackoverflow
Solution 4 - RegexAndrew SchulmanView Answer on Stackoverflow