2012-08-17 201 views
1

我想從兩個不同目錄的文本文件中提取column1和column7。這些目錄中的文件名稱相同。我需要將輸出保存到另一個目錄。用bash,awk或sed從多個文件中提取多列

file1.txt in D1 directory 

column1 column2 column3 column7 
david 45.2  14.6 45.0 
grecy 12.0  0.0 12.0 
anjal 23.2  321.0 34.5 

file1.txt in D2 directory 

column1 column2 column3 column7 
david 45.2  14.6 56.0 
grecy 10.0  0.0 12.0 
moha  23.1  321.0 334.5 

output format (save the output as file1.txt in D3 directory) 

column1 column1 column7 column7 
david  david 45.0 56.0 
grecy  grecy 12.0 12.0 
anjal  moha  34.5 334.5 

您的意見將不勝感激。

回答

3

一個快速的方法使用pasteawk

paste D1/file1.txt D2/file1.txt | awk '{ printf "%s\t%s\t%s\t%s\n", $1, $5, $4, $8 }' > D3/file1.txt 

結果:

column1 column1 column7 column7 
david david 45.0 56.0 
grecy grecy 12.0 12.0 
anjal moha 34.5 334.5 

編輯:要處理多個文件,你可以使用bash的循環:

for i in D1/*.txt; do paste "$i" D2/${i/D1\//} | awk '{ printf "%s\t%s\t%s\t%s\n", $1, $5, $4, $8 }' > D3/${i/D1\//}; done 
+0

感謝您的回答。您的代碼僅適用於單個文件。你能提供多個文件的代碼嗎? – user1606106 2012-08-17 07:25:48

+0

@ user1606106:我已經更新了處理多個文件的答案。 HTH。 – Steve 2012-08-17 10:58:19

+0

太棒了!謝謝。 – user1606106 2012-08-18 02:29:39

0
awk '{ 
    a1=$1;b1=$4; 
    getline <"D2/file1.txt"; 
    print a1,$1,b1,$4 
}' D1/file1.txt >D3/file1.txt 
0
join -j 1 -o 1.1,2.1,1.7,2.7 <(D1/file1.txt | sort -k1,1) <(sort -k1,1 D2/file1.txt) > D3/file1.txt