How to produce cartesian product in bash?

后端 未结 3 1013
耶瑟儿~
耶瑟儿~ 2020-12-06 17:04

I want to produce such file (cartesian product of [1-3]X[1-5]):

1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
2 4
2 5
3 1
3 2
3 3
3 4
3 5

I

3条回答
  •  孤街浪徒
    2020-12-06 17:47

    A shorter (but hacky) version of Rubens's answer:

    join -j 999999 -o 1.1,2.1 file1 file2
    

    Since the field 999999 most likely does not exist it is considered equal for both sets and therefore join have to do the Cartesian product. It uses O(N+M) memory and produces output at 100..200 Mb/sec on my machine.

    I don't like the "shell brace expansion" method like echo {1..100}x{1..100} for large datasets because it uses O(N*M) memory and can when used careless bring your machine to knees. It is hard to stop because ctrl+c does not interrupts brace expansion which is done by the shell itself.

提交回复
热议问题