Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have two files:

file1:

A,D
B,E
C,F

file2:

G,H,I
J,K,L

Using awk, I want to print:

A,D
B,E,I
C,F,L

How can I use awk to achieve this?

share|improve this question
1  
What is the relation between the 2 files? Is it a one one one comparison? –  Guru Dec 21 '12 at 11:49
    
@Guru, I do not understand what you're asking. File2 looks exactly like the above. –  nowy1 Dec 21 '12 at 12:09
    
@nowy1 : How will the output be if the file1 has 5 lines in it? –  Guru Dec 21 '12 at 12:11
3  
It's unclear from your sample how the files should be merged in the general case. –  Stéphane Chazelas Dec 21 '12 at 12:19
    
@Stephane Chazelas, See my edit. I changed the question and its description. You should now be clear. –  nowy1 Dec 21 '12 at 12:31

1 Answer 1

up vote 5 down vote accepted

I'll assume that extra field from the n lines of file2 should be appended to the last n lines of file1:

awk -F, -v OFS=, 'FNR==NR {a[FNR]=$3; next} {print $0, a[FNR]}' <(tac file2) <(tac file1) | tac
paste -d, <(tac file1) <(cut -d, -f3- <(tac file2)) | tac

These solution add a trailing comma to the first line. You can remove it by piping the above through sed 's/,$//'

share|improve this answer
    
See my edit. The files have a different number of lines (file1 -> 3 lines; file2 -> 2 lines). –  nowy1 Dec 21 '12 at 12:36
    
This is a good solution. Thank you. –  nowy1 Dec 21 '12 at 12:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.