2012-08-14 118 views
3

考虑这个文本文件:grep的正则表达式

TEST FILE : test       #No match 
             #No match 
Run grep "1133*" on this file   #Match 
             #No match 
This line contains the number 113.  #Match 
This line contains the number 13.  #No match 
This line contains the number 133.  #No match 
This line contains the number 1133.  #Match 
This line contains the number 113312. #Match 
This line contains the number 1112.  #No match 
This line contains the number 113312312. #Match 
This line contains no numbers at all. #No match 

怎样的grep命令评估1133*正则表达式?

为什么包含113的行是正值?

正则表达式1133*意在表示任何东西比 查找包含字1133+anything else所有行?

该示例可在tldp文档页面找到。

+1

1133 \ *匹配113或1133或11333等,或“无论站在\ *之前的元素出现零次或多次出现”。 – bobah 2012-08-14 13:22:05

+1

您将从学习正则表达式的基础知识(例如[here](http://regex.learncodethehardway.org/book/))中获得巨大的收益。 – huon 2012-08-14 13:24:32

回答

8

您正在考虑shell通配符,其中*与任何内容匹配。在regular expressions中,*quantifier,其意味着任何紧接其之前的“零个或多个”,在这种情况下是3

因此,您的表达意味着113后跟零个或多个3 s。

1

尝试 grep的 “1133 $” 或 的grep “^ 1133 $”

其中^是该行的开始和$是如果您的订单是假设3行

结束列: AAA 113 BBBB

猫file.txt的| awk的 '{打印$ 2}' | grep的 “^ $ 1133” |厕所-l

要确保你只着眼于特定的列