2

I was trying a multiple grep search, but for some reason it wasn't working:

Input:

What time is it in India
Time in Israel
Dogs are awesome
I want chocolate cake

Desire Output:

What time is it in India
chocolate cake

I used the command:

grep "(What time is it)|(chocolate cake)" inputfile.txt

However I got the an empty output instead. Would you know why this is going wrong?

2

2 Answers 2

3

You have to escape the pipe (|) because it is a special character.

grep "what time is it\|chocolate cake" inputfile.txt

The parens in your regex are superfluous and can be left off. If you leave them, they must also be escaped:

grep "\(what time is it\)\|\(chocolate cake\)" inputfile.txt
Sign up to request clarification or add additional context in comments.

Comments

1

Use egrep instead of grep. grep does not understand regexp you used:

$ egrep "(what time is it)|(chocolate cake)" input.txt 
what time is it in India
i want chocolate cake

More precisely, man grep on modern Unix-like system tells:

In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, +, {, \|, (, and ).

So, following will work with the same result:

grep "\(what time is it\)\|\(chocolate cake\)" input.txt

1 Comment

or similarly, grep -e 'string1' -e 'string2' input.txt

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.