Bash脚本循环遍历子目录并写入文件

时间:2014-10-18 05:47:31

标签: bash shell unix sh

我不知道我花了很多时间处理这个问题。我需要写脚本。脚本应该通过当前目录中的子目录递归循环。它应检查每个目录中的文件计数。如果文件计数大于10,则应将这些文件的所有名称写入名为" BigList"的文件中。否则它应写入文件" ShortList"。这看起来应该是

---<directory name>
<filename>
<filename>
<filename>
<filename>
....
---<directory name>
<filename>
<filename>
<filename>
<filename>
....

我的脚本仅在子目录不依次包含子目录时才有效。 我很困惑。因为它没有像我期望的那样工作。在我的任何编程语言上写这个都需要不到5分钟。 请帮忙解决这个问题,因为我不知道该怎么做。 这是我的剧本

#!/bin/bash
parent_dir=""
if [ -d "$1" ]; then
    path=$1;
else
    path=$(pwd)
fi
parent_dir=$path
loop_folder_recurse() { 
    local files_list=""      
    local cnt=0
    for i in "$1"/*;do
        if [ -d "$i" ];then
            echo "dir: $i"
            parent_dir=$i               
            echo before recursion
            loop_folder_recurse "$i"
            echo after recursion
            if [ $cnt -ge 10 ]; then
                echo -e "---"$parent_dir >> BigList
                echo -e $file_list >> BigList
            else
                echo -e "---"$parent_dir >> ShortList
                echo -e $file_list >> ShortList
            fi
        elif [ -f "$i" ]; then
            echo file $i
            if [ $cur_fol != $main_pwd ]; then
                file_list+=$i'\n'
                cnt=$((cnt + 1))
            fi
        fi
    done
}
echo "Base path: $path"
loop_folder_recurse $path

1 个答案:

答案 0 :(得分:0)

我相信这可以做你想要的:

find . -type d -exec env d={} bash -c 'out=Shortlist; [ $(ls "$d" | wc -l) -ge 10 ] && out=Biglist; { echo "--$d"; ls "$d"; echo; } >>"$out"' ';'

如果我们不想将子目录计入截止值或在输出中列出它们,请使用此版本:

find . -type d -exec env d={} bash -c 'out=Shortlist; [ $(ls -p "$d" | grep -v "/$" | wc -l) -ge 10 ] && out=Biglist; { echo "--$d"; ls -p "$d"; echo; } | grep -v "/$" >>"$out"' ';'
相关问题