Reputation: 89
I have two text files. the first one looks like this:
a
b
c
another file looks like this:
1 2
3 4
I want to use bash scripts in Linux to merge these two files so that each row of the first file will be placed next to all the rows of the second file and output looks like this:
a 1 2
a 3 4
b 1 2
b 3 4
c 1 2
c 3 4
Any help would be appreciated
Upvotes: 1
Views: 430
Reputation: 6185
I'd probably be downvoted mercilessly, but I believe that these kind of tasks are better suited to Perl
or Python.
Here's a Python 2
solution:
$ cat 1col.tmp
a
b
c
$ cat 2col.tmp
1 2
3 4
$ cat merge.py
with open("1col.tmp") as col1f:
for c1 in col1f.readlines():
with open("2col.tmp") as col2f:
for c2 in col2f.readlines():
print c1.strip(), c2.strip()
$ python merge.py
a 1 2
a 3 4
b 1 2
b 3 4
c 1 2
c 3 4
Upvotes: 0
Reputation: 133458
try one more awk where it will give output in same order as Input_file1.
awk 'FNR==NR{a[++i]=$0;next} {c[++k]=$0} END{for(q=1;q<=i;q++){for(u=1;u<=k;u++){print a[q],c[u]}}}' Input_file1 Input_file2
Upvotes: 0
Reputation: 60058
In pure shell, you can simply do:
#Usage: the_script FirstFile SecondFile
while read -r l1; do
while read -r l2 ; do
echo "$l1 $l2"
done <"$2"
done <"$1"
but the files better not be large, because the shell reads aren't very efficient (they make a syscall for each byte).
Upvotes: 1
Reputation: 784998
You can use awk
like this:
awk 'NR==FNR{a[++n]=$0; next} {for (i in a) print $0, a[i]}' file2 file1
a 1 2
a 3 4
b 1 2
b 3 4
c 1 2
c 3 4
Reference: Effective AWK Programming
Upvotes: 3