1

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?

Wara
  • 304
  • 2
  • 11

2 Answers2

4

Same expected output can be achieved without awk also

$ cat file1
a 1 2 3 
b 1 2 3
c 1 2 3
d 1 2 3

$ cat file2
hola
l m  n o p q 

$ pr -mtJS' '  file1 <(tail -n +2 file2)
a 1 2 3  l m  n o p q
b 1 2 3 
c 1 2 3 
d 1 2 3 

$ paste -d ' '  file1 <(tail -n +2 file2)
a 1 2 3  l m  n o p q 
b 1 2 3
c 1 2 3
d 1 2 3
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
2
$ 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.
CWLiu
  • 3,913
  • 1
  • 10
  • 14