0

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?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Jo0l
  • 1
  • 1
  • If this is tagged `bash`, are you okay with answers that use bash builtins _instead_ of using `paste`? – Charles Duffy Apr 22 '22 at 21:03
  • 1
    not possible with `paste`, far as I can tell. You're really looking for the *set product* of the lines from both files, and that's not something `paste` is useful for. In all honesty, this sounds trivial to do with Python's `collections` module and sufficiently hard and slow in bash scripting to justify doing this bit in Python. – Marcus Müller Apr 22 '22 at 21:04
  • _nod_. `paste -d ''` would give you `a1` `b2` `c3`, which is the only thing it's designed to do. It's not a tool designed or documented to calculate cross products. – Charles Duffy Apr 22 '22 at 21:05
  • Hello @CharlesDuffy yes is inside a bash script, any alternative that is not paste? – Jo0l Apr 22 '22 at 21:12
  • Hello @MarcusMüller any example to do this on python? – Jo0l Apr 22 '22 at 21:13
  • https://docs.python.org/3/library/itertools.html#itertools.product ; as files can be read line-wise if `open`ed in text mode, you can directly pass `open("List1")` and `open("List2")` as arguments to `itertools.product(…)` – Marcus Müller Apr 22 '22 at 21:25

4 Answers4

2

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
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
1

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
Cyrus
  • 84,225
  • 14
  • 89
  • 153
1

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.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

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)
tshiono
  • 21,248
  • 2
  • 14
  • 22