Search code examples
awkmerging-data

Merging two files by ignoring a line with AWK


I have two files: file 1:

a 1 2 3 
b 1 2 3
c 1 2 3
d 1 2 3

file 2:

hola
l m  n o p q 

Now I want to merge them in one single file by ignoring the header of file 2 like this:

a 1 2 3 l m n o p q 
b 1 2 3
c 1 2 3
d 1 2 3

Does anyone have an idea how to do this?


Solution

  • $ awk 'NR==FNR{if(NR>1)a[NR-1]=$0;next}{print $0,a[FNR]}' file2 file1
    a 1 2 3 l m  n o p q 
    b 1 2 3
    c 1 2 3
    d 1 2 3
    

    Brief explanation,

    • NR==FNR{if(NR>1)a[NR-1]=$0;next}: in file2, omit the header and save from the second record to a[NR-1]. Note: this would also work as the lines in file2 grow up
    • print $0,a[FNR]: print the combination of the content of $0 in file1 and a[FNR]. FNR would be the record number in file1.