如何將一列新增至另一個文件

如何將一列新增至另一個文件

假設這是我的文件,其名稱為 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 也有可能較少的行數比 file1 多,下面的程式碼負責正確添加列,以及可能添加更多列:

#!/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]+"  ")

相關內容