2015-10-20 116 views
2

我在文件夾中包含一個或多個行的多個txt文件。每個文件名稱都是一個電子郵件地址,其中包含不同的電子郵件地址。從多個文件構建csv文件

例如,我有我的文件夾中的3個文件:

每個文件的內容:

cat [email protected] 
[email protected] 
[email protected] 

cat [email protected] 
[email protected] 

cat [email protected] 
[email protected] 
[email protected] 
[email protected] 

我想建立一個包含這些數據只有一個文件:

[email protected];[email protected] 
[email protected];[email protected] 
[email protected];[email protected] 
[email protected];[email protected] 
[email protected];[email protected] 
[email protected];[email protected] 
+0

[在Bash中通過文件內容循環?](http://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash) – grimsock

回答

3

lists_merge.sh

#!/usr/bin/env bash 

shopt -s nullglob; 
for fname in *.txt; 
do 
    while read line; 
    do 
    printf "%s;%s\n" "$fname" "$line"; 
    done <"$fname"; 
done; 

輸出

$ ./lists_merge.sh 
[email protected];[email protected] 
[email protected];[email protected] 
[email protected];[email protected] 
[email protected];[email protected] 
[email protected];[email protected] 
[email protected];[email protected] 

注:腳本假設與分發列表文本位於同一目錄中 文件。將不承擔任何其他文本文件都在此目錄中


參考

nullglob info

+0

你爲什麼使用''shopt -s nullglob'行'? – gpupo

+0

這是爲了處理glob沒有* .txt匹配的情況。在這種情況下,bash將拋出一個沒有nullglob選項的錯誤。另請參見[此問題](http://stackoverflow.com/questions/2937407/test-whether-a-glob-has-any-matches-in-bash) – amdixon

+0

您可以安全地從腳本中刪除所有分號 - 它們只有當您在一行上放置兩個單獨的語句時才需要。 –

1

您可以使用sed

for emailfile in *.txt; do 
    email=${emailfile%.txt} 
    sed "s:^:$email;:" "$emailfile" 
done 

這將失敗,如果一個電子郵件ID有一個冒號(:),但我懷疑你會有這樣一個例子。