Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

suppose this is my file which its name is myFile1

1 10
2 20
3 30
4 40
5 50
6 60

know I want to add my another columns to this. This column is on the file which is myFile2.

10
11
12
13
14
15
16

. is there any way to add myFile2 to myFile1 to create this table :

1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
share|improve this question

2 Answers 2

up vote 2 down vote accepted

paste is pretty handy here but it'll punish you if the number of values is unequal:

$ paste -d' ' myFile{1,2}
1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
 16

If you wanted to arbitrarily limit the lines used in the second file to the first, you can, it's just going to be a bit slower and use more RAM (not that it matters on such a small data set).

$ paste -d' ' myFile1 <(head -n$(cat myFile1 | wc -l) myFile2)
1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
share|improve this answer
    
16 on the second file :-D –  lion Jul 25 at 8:36
    
Oli I am sure you go to paradise. –  lion Jul 25 at 8:51

Could not resist adding the verbose option (python script)

#!/usr/bin/env python3

with open("file1") as l:
    l = [item.replace("\n", "") for item in l]

with open("file2") as l2:
    l2 = [item.replace("\n", "") for item in l2]

for item in [l[i]+" "+l2[i] for i in range(0, len(l))]:
    print(item)

>>> 
1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
>>> 

To immediately write the changes to file1, the code would be:

#!/usr/bin/env python3

with open("file1", "r") as l:
    l = [item.replace("\n", "") for item in l]

with open("file2", "r") as l2:
    l2 = [item.replace("\n", "") for item in l2]

with open("file1", "wt") as edit:
    for item in [l[i]+" "+l2[i] for i in range(0, len(l))]:
        edit.write(item+"\n")

In case there is also a possibility that file2 has less rows than file1, the code below takes care of correct adding of the column, and possible addition of more columns:

#!/usr/bin/env python3

with open("file1", "r") as l1:
    l1 = [item.replace("\n", "") for item in l1]

with open("file2", "r") as l2:
    l2 = [item.replace("\n", "") for item in l2]

for i in range(0, len(l1)):
    try:
        print(l1[i]+" "+l2[i])
    except IndexError:
        print(l1[i]+"  ")
share|improve this answer

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.