4

I want to add the second column of file2 to file1, that contains a number an unknown number of columns, so becoming the last column of file1. In this aim, I tried to create a file3 composed by pasting a file1 and only the second column of file2:

file1:

col11  col12  col13  ...  col1n

file2:

col21  col22  col23  ...  col2m

new file1 or file3:

col11 col12  ...  col1n  col22

I'm using the command:

awk '{ print $0 > "file3"; getline<"file2"; print $2 > "file3" }' file1 &

but the arguments of the col22 instead of forming the last column of the new file will go on a new line.

Someone can help me to find and correct the error or also in finding a more effective solution?
My operating system is fedora12.

  • To repaire you script just change first print to printf "%s", – Costas Nov 11 '14 at 11:01
1
awk '{f1 = $0; getline<"file2"; print f1, $2}' < file1 > file3

The output file will have the same number of lines as file1, so the last column will be empty for the last lines if file2 is shorter, and the last values in file2 will be ignored if it's longer.

Alternatively, as suggested by Costas:

awk '{getline f1 <"file1" ; print f1,$2}' < file2 > file3

That time though, file3 will have the same number of lines as file2. That means the ordering of columns will be affected if file2 is longer than file1.

With:

awk '{print $2}' < file2 | paste file1 - > file3

file3 will have the same number of lines as the biggest of file1 and file2. No data will be discarded, but as above, if file2 is longer than file1, the last lines in file3 will have file2's data in the first/second column.

  • What do you think to make script shorter a little awk '{getline f1 <"file1" ; print f1,$2}' < file2 > file3 – Costas Nov 11 '14 at 10:22
  • @Costas, yes, that works too and looks nicer. There would be a difference though if file1 and file2 don't have the same number of lines. – Stéphane Chazelas Nov 11 '14 at 10:25
  • Who knows what file (1 or 2) is have more lines? – Costas Nov 11 '14 at 10:28
  • file1 and file2 have the same number of lines. – gloria Nov 11 '14 at 11:31
  • All the solutions you've proposed work. Thanks to all! – gloria Nov 11 '14 at 11:33
0

Try

$ awk 'NR==FNR{a[NR]=$2;next}{print $0,a[FNR]}' file2 file1
col11 col12 col13 ... col1n col22

The {a[NR]=$2;next} part will be executed only for first file in the list (file2), and when awk processes the second file (file1) we print the whole line of file1 and add table element a[FNR] which holds value of second field of file2.

  • BTW, you can perform this task also with paste and cut tools: paste -d' ' file1 <(cut -d' ' -f2 file2) – jimmij Nov 11 '14 at 9:18
  • I suspect the OP's files have more than one line though. – Stéphane Chazelas Nov 11 '14 at 10:03

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.