Issue with Joining lines from two files

Hi,
I have two text files, that need their data joining/concatenation. 'Paste' works for this.
But have an issue when there is mismatch in number of rows in each file.
E.g.
(main file) File1 - has 20 rows
File2 - has 30 rows.
Command 'paste file1 file2 > file3' joins all lines.
I want the output for only 20 rows, i.e. the joining for only the number of rows present in first file(file1) and dont want extra rows.

Can you please help me out on this?

Regards,
Sharath.

Try this. file1 is the file with fewer lines.

#!/bin/bash
PATH=/usr/bin:/bin
export PATH

exec 3<file1
exec 4<file2

while read a 0<&3; do
        read b 0<&4
        echo $a $b
done
paste t1 t2 | head -n `wc -l t1 | cut -d' ' -f1`
  • paste t1 t2 -- paste both files
  • head -n `wc -l t1 | cut -d' ' -f1`
    [list]
  • number of rows from the first file.
    [/list]

with awk but it would be better if you have showed the file format.

 
awk 'NR==FNR{_[$1]=1;next}_[$1]' file1 file2

awk is the best way to go. If you want you can also use the join command but both files have to be sorted on the common key which is, in my opinion, a disadvantage compared to awk.

$ cat file1
id1 file1_item1
id2 file1_item2
id3 file1_item3

$ cat file2
id1 file2_item1
id2 file2_item2
id3 file2_item3
id4 file2_item4
id5 file2_item5

$ join -11 -21 file1 file2
id1 file1_item1 file2_item1
id2 file1_item2 file2_item2
id3 file1_item3 file2_item3