2017-03-18 21 views
-1

我有兩個文件。文件1和文件2的內容如下。我想在文件2中找到對文件1的值。如何在不使用grep的情況下從另一個文件中搜索值?

搜索我下面的查詢,但我無法理解。

查詢:

cat file1 | awk -F ',' 'BEGIN{while(getline<"file2"){OFS=",";a[$2]=$1","$2","$3}} {print $0,a[$1]}' >> Final 

文件1

173 
149 
133 
162 

文件2

140, dog 
145, cat 
149, rat 
133, frog 
160, lion 
162, total 

請注意:正常的grep需要大量的時間,文件2的大小是非常大的。

+0

只是爲了記錄AWK使得絕對匹配而做的grep模式匹配。在grep鍵中匹配鍵,在awk中不是,除非你使用awk模式匹配(〜/ pattern /) –

+1

@GeorgeVasiliou我認爲應該是s/absolute/string /和s/pattern/regexp /。不要使用「模式」這個詞,因爲它非常含糊 - 總是使用「string」或「regexp」,無論你當時是什麼意思。並且要清楚你正在談論用戶特定的發佈腳本,而不是一般的awk。 Vaibhav - 如果您正在考慮使用getline,請確保您先閱讀並完全理解http://awk.freeshell.org/AllAboutGetline上討論的所有警告。 –

+0

@GeorgeVasiliou好的,我在http://unix.stackexchange.com/a/352304/133219上發佈了awk解決方案。 –

回答

2

通知,無需餵食cat

$ awk -F, 'NR==FNR{a[$1];next}$1 in a' f1 f12 
149, rat 
133, frog 
162, total 

解釋:

awk -F, ' # set delimiter to , 
NR==FNR{ # process the first file 
    a[$1] # hash the keys to a 
    next # off to the next record 
} 
$1 in a  # for the second file, if key ($1) is found in hash, output record 
' f1 f2  # file order is important 
相關問題