1

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

1
  • What have you tried so far ? It seems like something that could easily be done with 2 imbricated while read loops, or an awk script Commented Jul 28, 2017 at 8:43

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.