2013-01-10 83 views
3

對不起,這個問題的標題是有點混亂,但我想不出其他的東西。 我試圖做這樣的事情在不同的文件中grep「cat命令的輸出 - 每一行」

cat fileA.txt | grep `awk '{print $1}'` fileB.txt 

的fileA包含100線,而FILEB包含100萬線。

我想要的是從fileA獲得id,grep在不同的file-fileB中的id並打印該行。

e.g fileA.txt 
1234 
1233 

e.g.fileB.txt 
1234|asdf|2012-12-12 
5555|asdd|2012-11-12 
1233|fvdf|2012-12-11 

預計產量

1234|asdf|2012-12-12 
1233|fvdf|2012-12-11 

回答

4

awk中能做到這一點的工作做好:

awk -F'|' 'NR==FNR{a[$0];next;}$1 in a' fileA fileB 

看到測試:

kent$ head a b 
==> a <== 
1234 
1233 

==> b <== 
1234|asdf|2012-12-12 
5555|asdd|2012-11-12 
1233|fvdf|2012-12-11 

kent$ awk -F'|' 'NR==FNR{a[$0];next;}$1 in a' a b 
1234|asdf|2012-12-12 
1233|fvdf|2012-12-11 

編輯

附加說明:

-F'|' #| as field separator (fileA) 
'NR==FNR{a[$0];next;} #save lines in fileA in array a 
$1 in a #if $1(the 1st field) in fileB in array a, print the current line from FileB 

進一步的細節我不能在這裏解釋一下,對不起。例如awk如何處理兩個文件,什麼是NR和什麼是FNR ..我建議,如果接受的答案不適用於您,請嘗試使用此awk行。如果你想深入一點,請閱讀awk的一些教程。

+1

+1這應該是可以接受的答案,例如'grep -f'會無意中匹配諸如'1234'和'11234'之類的東西。 – Steve

+0

@Kent你會介意解釋'NR == FNR {a [$ 0]; next;} $'1'在' – priyank

+0

我試圖弄清楚我是否想在特定列中執行grep ... grep -f wont工作。 – priyank

1

如果ID是在不同的線路,你可以在grep使用-f選項,例如:

​​

cut命令將確保只有在使用grep搜索的模式中搜索第一個字段。

從手冊頁:

-f FILE, --file=FILE 
Obtain patterns from FILE, one per line. 
The empty file contains zero patterns, and therefore matches nothing. 
(-f is specified by POSIX.) 
+0

-1,一個ID(在fileA中)是2012? – Kent

+0

@Kent我想我們也必須使用'cut'。 – squiguy

+0

我認爲你的grep需要 - 也是。你不想在fileA中的行是正則表達式模式嗎? – Kent

11

擺脫catawk乾脆:單獨

grep -f fileA.txt fileB.txt 
+0

謝謝我沒想到這是這麼簡單。 – priyank