2

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?

  • 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
5

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/,$//'

  • See my edit. The files have a different number of lines (file1 -> 3 lines; file2 -> 2 lines). – nowy1 Dec 21 '12 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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