サブディレクトリを繰り返し、ファイルをリンクし、繰り返し番号を使用する必要があります。

サブディレクトリを繰り返し、ファイルをリンクし、繰り返し番号を使用する必要があります。

3つの異なるサブディレクトリにあるファイルを1つのファイルにリンクしようとしています。各サブディレクトリのファイル名はまったく同じです。ループを使用してサブディレクトリを繰り返してから、新しいディレクトリの新しく名前付きリンクファイルに繰り返し番号を入力したいと思います。たとえば、ディレクトリ構造は次のようになります。

Foo
|||
||Bar3
|Bar2
Bar1

各Bar(?)フォルダには、File1、File2、File3という名前のファイルが含まれています。

同じ名前のファイルを数字を含む新しい名前のより大きなファイルにリンクしたいと思います。

cat Foo/Bar1/File1 Foo/Bar2/File1 Foo/Bar3/File1 > /combined_files/all_file1

cat Foo/Bar1/File2 Foo/Bar2/File2 Foo/Bar3/File2 > /combined_files/all_file2

cat Foo/Bar1/File3 Foo/Bar2/File3 Foo/Bar3/File3 > /combined_files/all_file3

Foo私が使用できるディレクトリから:

for number in {1..3}
    do
    cat Bar1/File$number\_* Bar2/File$number\_* Bar3/File$number\_* > combined_files/'all_files'$number
    done
exit

しかし、より多くのバーのディレクトリとファイルについては、より一般的なスクリプトが必要です。私は次のようなものが欲しい

files=`ls ./Run1/ | wc -l`   #to count the number of files and assign a number
For n in {1..$files}
    do
    cat Bar1/File$n\_* Bar2/File$n\_* Bar3/File$n\_* > combined_files/'all_files'$n
    done

しかし、詰まっています。

ベストアンサー1

#!/bin/sh

for pathname in Foo/Bar1/File*; do
    filename=${pathname##*/}
    cat "$pathname" \
        "Foo/Bar2/$filename" \
        "Foo/Bar3/$filename" >"combined/all_$filename"
done

これは、名前が一致するすべてのファイルを繰り返しますFile*Foo/Bar1パターンが実際に興味のある名前と正確に一致すると仮定します)。

これらのファイルごとに生成されたパス名のファイル名部分を抽出します(これは次の方法で$filename行うこともできます)。filename=$(basename "$pathname")次に、Foo/Bar2ソースファイルをディレクトリ内の対応するファイルに関連付けて、Foo/Bar3結果をall_$filename別のディレクトリの新しいファイルに書き込みます。


いくつかのエラーチェック後:

#!/bin/sh

for pathname in Foo/Bar1/File*; do
    if [ ! -f "$pathname" ]; then
        printf '% is not a regular file, skipping\n' "$pathname" >&2
        continue
    fi

    filename=${pathname##*/}

    if [ -f "Foo/Bar2/$filename" ] &&
       [ -f "Foo/Bar3/$filename" ]
    then
        cat "$pathname" \
            "Foo/Bar2/$filename" \
            "Foo/Bar3/$filename" >"combined/all_$filename"
    else
        printf 'Missing %s or %s\n' "Foo/Bar2/$filename" "Foo/Bar3/$filename" >&2
    fi
done

サブディレクトリの数が異なるBarNバリアントも許可されます。これは推定BarNディレクトリには1から大きな数字まで番号が付けられています。

#!/bin/sh

# This is just used to count the number of BarN subdirectories.
# The number of these will be $#.
set -- Foo/Bar*/

for pathname in Foo/Bar1/File*; do
    filename=${pathname##*/}

    n=1
    while [ "$n" -le "$#" ]; do
        if [ ! -f "Foo/Bar$n/$filename" ]; then
            printf '%s missing, %s will be incomplete\n' \
                "Foo/Bar$n/$filename" "combined/all_$filename" >&2
            break
        fi

        cat "Foo/Bar$n/$filename"
        n=$(( n + 1 ))
    done >"combined/all_$filename"
done

おすすめ記事