2012-08-14 136 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

要確保你只着眼於特定的列