2012-03-22 86 views
0

在我的主文件夾中,我有多個子文件夾,每個子文件夾包含多個文件。我想合併這些文件在每個子文件夾中。合併每個文件夾中的文件(貓)Unix

所以我試圖做這樣的事情:

cd ../master-folder 

for file in $(find . -name "*.txt"); 
do 
cat "all the text files in this sub folder" > "name of the subfolder.txt" 
rm "all the previous text files excluding the merged output obviously" 
    done 

感謝幫助!謝謝。

+0

附加順序是否重要? – paul 2012-03-22 20:45:18

+0

嘗試使用-exec遞歸查找。它會需要一些逃避巫術,但它可能是可行的 – 2012-03-22 20:47:13

+0

順序並不重要。 – dawnoflife 2012-03-22 20:53:33

回答

2

我會做這樣的,如果這些文件的順序並不重要:

for i in $(find -maxdepth 1 -mindepth 1 -type d) 
do 
    find $i -name '*.txt' -type f -exec cat {} >> $i-list.txt \; 
    find $i -name '*.txt' -type f -exec rm {} \; 
done 

先找查找子目錄。

第二個附加的所有子文件的內容到一個文件

第三個刪除子文件。

如果有遞歸子目錄,這不起作用。如果你想要這個,刪除'-maxdepth 1'

+0

'$ i-list'是否會包含名稱中的路徑? – dawnoflife 2012-03-22 20:58:18

+0

這給了我一個''-exec'錯誤的缺失參數。 – dawnoflife 2012-03-22 21:02:49

+0

它將包含目錄名稱plus -list.txt。這條路是什麼意思?儘管如此,如果您使用遞歸方法,txt文件將位於列出的目錄的父目錄 – paul 2012-03-22 21:04:28

2

爲什麼不能以遞歸方式訪問每個目錄?

#!/bin/bash                  

shopt -s nullglob # Make failed globs expand to nothing 

function visit { 
    pushd "$1" 
    txts=(*.txt) 
    if ((${#txts[@]} > 0)) 
    then 
     cat "${txts[@]}" > "${PWD##*/}.txt" 
     rm -f "${txts[@]}" 
    fi 
    for dir in */ 
    do 
     visit "$dir" 
    done 
    popd 
} 

visit /path/to/start/dir 

警告::沿着線的東西,如果你有一個在你的目錄樹中創建循環符號鏈接,那麼這是一個壞主意。

相關問題