Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have two files:





Using awk, I want to print:


How can I use awk to achieve this?

share|improve this question
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
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
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


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.