Home > Back-end >  Bash get all permutations of lines from two files concatenated without intervening whitespace?
Bash get all permutations of lines from two files concatenated without intervening whitespace?

Time:04-23

i making a proyect and i want to join to files using paste, but i want to do this

List1         List2
a               1
b               2
c               3

Result
a1
a2
a3
b1
b2
b3
c1
c2
c3

Is there a way to get that result with paste?

CodePudding user response:

With bash and two simple loops:

while read -r l1; do while read -r l2; do echo "$l1$l2"; done <list2; done <list1

Output:

a1
a2
a3
b1
b2
b3
c1
c2
c3

CodePudding user response:

Feeding the files in reverse order to awk:

$ awk 'FNR==NR{a[  cnt]=$1;next}{for (i=1;i<=cnt;i  ) print $1 a[i]}' f2 f1
a1
a2
a3
b1
b2
b3
c1
c2
c3

Expanding on this hack:

$ join -j 9999999 -o 1.1,2.1 f1 f2 | sed 's/ //'

a1
a2
a3
b1
b2
b3
c1
c2
c3

CodePudding user response:

With python would you please try the following (as Marcus Müller comments):

#!/usr/bin/python

import itertools

with open('list1', 'r') as f1:
    i1 = f1.read().splitlines()
with open('list2', 'r') as f2:
    i2 = f2.read().splitlines()
for v1, v2 in itertools.product(i1, i2):
    print(v1   v2)

CodePudding user response:

With bash, reading each file once:

mapfile -t list1 < file1
mapfile -t list2 < file2
brace_expr=$(IFS=,; printf '{%s}{%s}' "${list1[*]}" "${list2[*]}")
eval "printf '%s\n' $brace_expr"

BUT this is vulnerable to code injection: you'd better be 100% certain the contents of the files are safe.

  •  Tags:  
  • bash
  • Related