2016-08-18 86 views
0

我想從一個巨大的文件看起來像這樣提取:正則表達式給出與grep

..... 
G: Quantity 000001, removing 4 binary files 
A: some stuff 
..... 
G: some other stuff 
G: some infos 
..... 
G: Quantity 000002, removing 1 binary files 
.... 
A: some data 
.... 
G: Quantity 000003, removing 41 binary files 
..... 

所有行「G:產品數量??????,除去*二進制文件」。

我正在用bash語法編寫這個模式,因爲它是我最熟悉的模式,但grep不會將我的問號和星號解釋爲bash。什麼是相應的grep語法?

以下語法的工作原理:

grep "G:" filename | grep Quantity | grep removing 

,但它不使用任何正則表達式。

+0

'貓grep.txt | grep -e^G. * binary \ files $'類似的東西? –

+0

通過「bash語法」,您可能的意思是「globbing pattern」,儘管目的有些類似,但它不是一個正則表達式。谷歌'regexp教程'並採取它。 –

回答

2

在正則表達式中,匹配任何字符的方法是使用.

如果你想匹配任何字符N次,比如說.{N}。如果你想匹配至少一個,比如說.+。作爲這種情況下,你想匹配的數字,它可能是最好的說[0-9],而不是過於籠統.

grep -E 'G: Quantity [0-9]{6}, removing [0-9]+ binary files' file 

此命令將返回:

G: Quantity 000001, removing 4 binary files 
G: Quantity 000002, removing 1 binary files 
G: Quantity 000003, removing 41 binary files