2017-08-30 43 views
0

我正在從文件appliances_list.txt中讀取一個字符串。從文件讀取模式,grep只出現在第一個位置

appliances_list.txt包含

fridge 
dryer 
ironbox 
microwave 

我讀的文件是myappliances.txt。內容是

I have a fridge 
I have another fridge 
I have a refridgerator 
I have a microwave 
I have ironbox at home 
I have another microwave 
I have a hairdryer 

我使用

grep -o -m1 -f appliances_list.txt myappliances.txt 

的輸出被

fridge

我的期望的輸出是,每個串(完全匹配)的第一次出現

fridge 
microwave 
ironbox 

有人能指引我走向正確的方向嗎?

+1

歡迎SO。首先,請使用編輯器中的「{}」按鈕修復數據和代碼示例的佈局。謝謝。 –

+1

當然。謝謝詹姆斯。 – Nandu

+1

@jww Shell腳本仍在編程。 – o11c

回答

1

一個用awk:

$ awk 'NR==FNR{a[$1]=1;next}a[$2]==1{print $2;a[$2]++}' pattern sample 
Pattern1 
Pattern2 
Pattern3 

解釋:

$ awk '   # well, awk 
NR==FNR {   # for the first file 
    a[$1]=1  # hash each keyword and set it as 1 
    next   # next record 
} 
a[$2]==1 {  # second file, if the word in 2nd column was hashed and 1 
    print $2  # output it 
    a[$2]++  # and increase its value above 1 
}' pattern sample # mind the order 
+0

謝謝詹姆斯。我嘗試瞭解決方案。沒有打印:( – Nandu

相關問題