bash - 他のファイルで可能なすべての単語の組み合わせ

bash - 他のファイルで可能なすべての単語の組み合わせ

私は持っていますNファイルごとに1単語ずつ

ファイル1ファイル2ファイル3 ...
1_a 2_a 3_a
1_b 2_b 3_b
1_c 3_c

私はこれらのファイルをすべて取り出し、nワード(各ファイルごとに1つ)のすべての可能な組み合わせを生成するbashスクリプトを作成したいと思います。

私の例では、次の結果が必要です。

1_a 2_a 3_a
1_a 2_a 3_b
1_a 2_a 3_c
1_a 2_b 3_a
1_a 2_b 3_b
1_a 2_b 3_c
1_b 2_a 3_a
1_b 2_a 3_b
1_b 2_a 3_c
1_b 2_b 3_a
1_b 2_b 3_b
1_b 2_b 3_c
1_c 2_a 3_a
1_c 2_a 3_b
1_c 2_a 3_c
1_c 2_b 3_a
1_c 2_b 3_b
1_c 2_b 3_c

Pasteとawkでこれを試しましたが失敗しました。どうすればいいですか?

ベストアンサー1

処理するファイルがある場合は、再帰関数を使用して自分自身を呼び出すことができます。

#!/bin/bash

process () {
    local prefix=$1
    local file=$2
    shift 2
    while read line ; do
        if (($#)) ; then                  # There are still unprocessed files.
            process "$prefix $line" "$@"
        else                              # Reading the last file.
            printf '%s\n' "$prefix $line"
        fi
    done < "$file"
}

process '' "$@"

おすすめ記事