Text-Processing

將文本塊複製到另一個文件中的特定點

  • November 26, 2018

我試圖弄清楚如何將文本塊從一個文件移動到另一個文件的特定點。我有大量看起來像這樣的文件:

H                 -9.92247800    1.33807800   -0.69208300  
S                 -9.74392800    0.01073000   -0.55448800   
C                 -7.98603700    0.04294200   -0.19355700   
C                 -7.45325900   -1.23715800    0.02112600
...  

我想將數字列移動到以前看起來像這樣的文件:

...
0 1 0 1 0 1

H                0  H
S                0  H
C                0  H
C                0  H
...

之後應該是這樣的:

...
0 1 0 1 0 1

H                0 -9.92247800    1.33807800   -0.69208300 H
S                0 -9.74392800    0.01073000   -0.55448800 H
C                0 -7.98603700    0.04294200   -0.19355700 H
C                0 -7.45325900   -1.23715800    0.02112600 H
...

無論如何,是否可以為大量文件自動執行此操作?我知道我可以選擇一個塊,複製它,然後手動將其粘貼到另一個文件中,但是我有太多文件,這不可行。

數字塊始終在同一位置(行和列)開始和結束,我要粘貼到的位置始終在同一行和列。

不知道您是否支持 Python,並且可能有一種使用不同語言的簡潔方法,但 Python 可以通過以下方式做到這一點:

程式碼:

# describe where the text block is located
f1_start = 2, 18
f1_size = 4, 40
f2_start = 4, 19

# open all three files
with open('file1', 'rU') as f1, open('file2', 'rU') as f2, open('file3', 'w') as f3:
   
   # skip some lines in file1
   for _ in range(f1_start[0] - 1):
       f1.readline()
       
   # write first block of file2 to file3
   for _ in range(f2_start[0] - 1):
       f3.write(f2.readline())
       
   # read from and merge lines in file1 and file 2
   for _ in range(f1_size[0]):
       l1 = f1.readline()[f1_start[1]:f1_start[1] + f1_size[1]].rstrip()
       l2 = f2.readline()
       l3 = l2[:f2_start[1]] + l1 + l2[f2_start[1]:]
       f3.write(l3)
       
   # write remaining lines from file2 to file3
   while True:
       l2 = f2.read()
       if not l2:
           break
       f3.write(l2)

結果:

...
0 1 0 1 0 1

H                0 -9.92247800    1.33807800   -0.69208300 H
S                0 -9.74392800    0.01073000   -0.55448800 H
C                0 -7.98603700    0.04294200   -0.19355700 H
C                0 -7.45325900   -1.23715800    0.02112600 H
...

引用自:https://unix.stackexchange.com/questions/370527