The best alternative for a Cartesian product in bash is by far, as @fedorqui pointed out, to use a parameter extension. However, if your input is not easy to get (ie. If {1..3} and {1..5} are missing), you can simply use join .
For example, if you want to convert the Cartesian product of two ordinary files, for example "a.txt" and "b.txt", you can do the following. Firstly, two files:
$ echo -en {a..c}"\tx\n" | sed 's/^/1\t/' > a.txt $ cat a.txt 1 ax 1 bx 1 cx $ echo -en "foo\nbar\n" | sed 's/^/1\t/' > b.txt $ cat b.txt 1 foo 1 bar
Note that the sed command is used to add each line with an identifier. The identifier must be the same for all lines, and for all files, so join will give you a Cartesian product - instead of deferring part of the resulting lines. So, join looks like this:
$ join -j 1 -t $'\t' a.txt b.txt | cut -d $'\t' -f 2- ax foo ax bar bx foo bx bar cx foo cx bar
After combining both files, cut used as an alternative to deleting a column with a previously added column.
source share