2016-08-17 54 views
1

我有一個相當不整潔的CSV文件作爲字段分隔符;。在字段1中,我有一個名稱,在字段3或4中有地址詳細信息,用逗號分隔,其中包含一個未指定數量的條目,主要包括一個電子郵件地址。所以它看起來像這樣:使用awk裏面的grep

Doe, Jon; Some information ; some more information; di: address details, p: () 56789, F: 252470, [email protected]  
Miller, Mariella; Some information ; di: other address, p: (09876) 54321, [email protected]  
Brown, Sam; Other information ; di: other address with no e-mail, p: (09876) 54321 

我想從文件中提取電子郵件地址以及名稱。我能得到的名稱與

BEGIN {FS = ";"} 
/@/ {print $1} 

我可以用這個漂亮的grep查找電子郵件的地址:

grep -i -o "[A-Z0-9._%+-]\[email protected][A-Z0-9.-]\+\.[A-Z]\{2,4\}" mylist.csv 

我想有一個名爲grep的時候有在該行的@ ,導致這樣的輸出:

Doe, Jon, [email protected] 
Miller, Mariella, [email protected] 

但我不知道如何可以從awk調用grep。

+0

'awk'可以做所有的一切'grep'可以。使用外部工具幾乎沒有意義。 –

回答

2

可以使用gawk

$ gawk -F\; 'match($0, /(\[email protected][^@]+.)/, a){print $1", "a[1]}' file 
Doe, Jon, [email protected]  
Miller, Mariella, [email protected] 

documentation

如果正則表達式包含括號,陣列 的整數索引元件被設置爲包含字符串的匹配對應的部分 括號內的子表達式。

說明

match($0, /(\[email protected][^@]+.)/, a)將有助於我們在兩種方式比賽功能將只有在正則表達式捕獲mail地址,然後我們進入打印部分來展示最終結果。