假设这是我的文件,其名称为 myFile1
1 10
2 20
3 30
4 40
5 50
6 60
我知道我想将另一列添加到这里。此列位于文件 myFile2 上。
10
11
12
13
14
15
16
. 有没有办法将 myFile2 添加到 myFile1 来创建此表:
1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
答案1
paste
在这里非常方便,但是如果值的数量不平等,它会惩罚你:
$ paste -d' ' myFile{1,2}
1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
16
如果您想任意将第二个文件中使用的行限制为第一个文件,您可以,但它只会慢一点并且使用更多的RAM(对于这么小的数据集来说这并不重要)。
$ 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
答案2
无法抗拒添加详细选项(python 脚本)
#!/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
>>>
要立即将更改写入 file1,代码如下:
#!/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")
如果 file2 也有可能较少的行数多于文件 1,下面的代码负责正确添加列,以及可能添加更多列:
#!/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]+" ")