各サブディレクトリのファイルを繰り返し、条件を適用します。

各サブディレクトリのファイルを繰り返し、条件を適用します。

私のディレクトリには、複数のファイルを含む多くのサブディレクトリが含まれています(拡張子が.arのファイルだけに興味があります)。次に、各サブディレクトリを繰り返し確認する必要があります。たとえば、ファイル数が 4 の場合はそのファイルで操作を実行し、2 番目のサブディレクトリに戻ってファイルを確認し、=3 の場合はそのファイルで別のコマンドを実行します。 。 if文に非常に複雑な条件を適用する必要があることに注意してください。

これに似たもの

dir=$1

for sub_dir in $dir; do
    if the number of files in $sub_dir = 4; then
        do something or command line 
    if the number of files in $sub_dir = 3; then
       do another command
    if the number of files in $sub_dir < 3; then
    escape them

    fi
done

同様のプロセス用のテンプレートが必要です。

ベストアンサー1

サブディレクトリが最上位ディレクトリのすぐ下にあるとします。

#!/bin/sh

topdir="$1"

for dir in "$topdir"/*/; do
    set -- "$dir"/*.ar

    if [ "$#" -eq 1 ] && [ ! -f "$1" ]; then
        # do things when no files were found
        # "$1" will be the pattern "$dir"/*.ar with * unexpanded
    elif [ "$#" -lt 3 ]; then
        # do things when less than 3 files were found
        # the filenames are in "$@"        
    elif [ "$#" -eq 3 ]; then
        # do things when 3 files were found
    elif [ "$#" -eq 4 ]; then
        # do things when 4 files were found
    else
        # do things when more than 4 files were found
    fi
done

または以下を使用してくださいcase

#!/bin/sh

topdir="$1"

for dir in "$topdir"/*/; do
    set -- "$dir"/*.ar

    if [ "$#" -eq 1 ] && [ ! -f "$1" ]; then
        # no files found
    fi

    case "$#" in
        [12])
            # less than 3 files found
            ;;
        3)
            # 3 files found
            ;;
        4)
            # 4 files found
            ;;
        *)
            # more than 4 files found
    esac
done

ファイル名を必要とするコードブランチは、"$@"サブディレクトリ内のすべてのファイル名を参照するために使用されるか、個々のファイルを参照するために使用されます"$1"。ファイル名はスタートアップディレクトリを含むパス名"$2"です。$topdir

おすすめ記事