2012-03-22 56 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 

警告::沿着线的东西,如果你有一个在你的目录树中创建循环符号链接,那么这是一个坏主意。

相关问题