多个grep搜索

时间:2014-07-08 17:34:52

标签: linux grep

我正在尝试多次grep搜索,但由于某种原因它无法正常工作:

输入:

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

欲望输出:

What time is it in India
chocolate cake

我使用了命令:

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

但是我得到了一个空输出。你知道为什么会出错吗?

2 个答案:

答案 0 :(得分:3)

你必须逃避管道(|),因为它是一个特殊字符。

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

正则表达式中的parens是多余的,可以不用了。如果你离开他们,他们也必须逃脱:

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

答案 1 :(得分:1)

使用egrep代替grepgrep无法理解您使用的正则表达式:

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

更确切地说,现代类Unix系统上的man grep告诉:

  

在基本正则表达式中,元字符?,+,{,|,(和)   失去他们的特殊意义;而是使用backslashed版本\?,   +,{,\ |,(和)。

因此,以下将使用相同的结果:

grep "\(what time is it\)\|\(chocolate cake\)" input.txt
相关问题