2017-07-17 38 views
-2

我需要從下面的文件中grep一個表達式:請幫助我希望在磁盤@直到逗號之後grep這個單詞。python 2.7需要從一個文件中grep一個特定的字

cat out1 boot-device=/[email protected]/[email protected]/[email protected]/[email protected]/[email protected]/[email protected],0:a rootmirror rootdisk boot-device-index=0 
+0

grep的是一個shell工具。這是一個Python問題? – khelwood

+0

我的意思是想讓文字磁盤@直到逗號。請檢查以下內容:disk @ w5000cca025884d5d – aleem

+0

我認爲「grep」的意思是「使用正則表達式」? Python有一個庫。見下面: –

回答

0

是這樣的?它會打印出 「盤@ w5000cca025884d5d」

import re 
file_object = open("input", "r") 
for line in file_object:  
    m = re.search('.*[email protected](.*),.*', line) 
    if m: 
     print(m.group(1)) 
+0

非常感謝我能夠打印工作,但我不想要逗號。請檢查:disk @ w5000cca025884d5d, – aleem

+0

當然,只要將它移到()之外就像我上面所做的那樣。 –

+0

非常感謝它的工作。但是我的錯誤是我的要求是在磁盤@之後搜索表達式,並且在逗號之前少一個字符。我真的很抱歉。 – aleem

0

可能需要逃避逗號作爲特殊字符:

import re 

s = 'cat out1 boot-device=/[email protected]/[email protected]/[email protected]/[email protected]/[email protected]/[email protected],0:a rootmirror rootdisk boot-device-index=0' 
match = re.search(r'[email protected](.*)\,', s) 

if match: 
    print match.group(1) 

輸出:

w5000cca025884d5d 
+0

非常感謝它的工作。 – aleem

+0

從輸出我想刪除第一個和最後一個字母。這是我的要求。謝謝很多幫助。 – aleem

+0

好的,但沒有其他答案解決你的問題? – davedwards

相關問題