2015-09-25 57 views
-1

每個值增加一個特定的整數我有兩個文件是這樣的:追加兩列在Unix的

# step   distance    
      0 4.48595407961296e+01 
     2500 4.50383737781376e+01 
     5000 4.53506757198727e+01 
     7500 4.51682465277482e+01 
     10000 4.53410353656445e+01 

    # step distance    
      0 4.58854106214881e+01 
     2500 4.58639266431320e+01 
     5000 4.60620560167519e+01 
     7500 4.58990075106227e+01 
     10000 4.59371359946124e+01 

所以我想這兩個文件連接在一起,同時保持間距。 特別是,第二個文件需要記住第一個文件的結束值並從該文件開始計數。

輸出:

# step   distance    
       0 4.48595407961296e+01 
      2500 4.50383737781376e+01 
      5000 4.53506757198727e+01 
      7500 4.51682465277482e+01 
      10000 4.53410353656445e+01 
      12500 4.58854106214881e+01 
      15000 4.58639266431320e+01 
      17500 4.60620560167519e+01 
      20000 4.58990075106227e+01 
      22500 4.59371359946124e+01 

隨着鈣很容易做的問題是,間距需要是爲了工作,在這種情況下,計算使一塌糊塗。

回答

0
# start awk and set the *Step* between file to 2500 
awk -v 'Step=2500' ' 

    # 1st line of 1 file (NR count every line, from each file) init and print header 
    NR == 1 {LastFile = FILENAME; OFS = "\t"; print} 

    # when file change (new filename compare to previous line read) 
    # Set a new index (for incremental absolute step from relative one) and new filename reference 
    FILENAME != LastFile { StartIndex = LastIndex + Step; LastFile = FILENAME} 

    # after first line and for every line stating witha digit (+ space if any) 
    # calculate absolute step and replace relative one, print the new content 
    NR > 1 && /^[[:blank:]]*[0-9]/ { $1 += StartIndex; LastIndex = $1;print } 
    ' YourFiles* 
  • 結果將取決於文件的順序
  • 輸出分離器採用OFS值設置(此選項卡)
+0

工程就像一個魅力,非常感謝。 對我來說awk語法的理解很複雜,如果你有時間並且會指出一些解釋或參考,我可以在其中找到它們 – user2710445

+0

在源代碼中直接添加了一些註釋。有很多關於(g)awk的pdf,html或其他書籍將有助於更深入地理解 – NeronLeVelu

0

Perl來拯救!

#!/usr/bin/perl 
use warnings; 
use strict; 

open my $F1, '<', 'file1' or die $!; 
my ($before, $after, $diff); 
my $max = 0; 
while (<$F1>) { 
    print; 
    my ($space1, $num, $space2) = /^(\s*) ([0-9]+) (\s*)/x or next; 

    ($before, $after) = ($space1, $space2); 
    $diff = $num - $max; 
    $max = $num; 
} 

$before = length "$before$max"; # We'll need it to format the computed numbers. 

open my $F2, '<', 'file2' or die $!; 
<$F2>; # Skip the header. 
while (<$F2>) { 
    my ($step, $distance) = split; 
    $step += $max + $diff; 
    printf "% ${before}d%s%s\n", $step, $after, $distance; 
} 

程序會記住$ max中的最後一個數字。它還將前導空格的長度加上$ max之前的$ max來格式化所有將來的數字以佔據相同的空間(使用printf)。

你沒有表現出距離欄的對齊方式,即

 20000 4.58990075106227e+01 
     22500 11.59371359946124e+01 # dot aligned? 
     22500 11.34572478912301e+01 # left aligned? 

該計劃將保持一致,後者的方式。如果您想要前者,請使用與步驟列相似的技巧。

+0

非常感謝,但我沒有Perl的專家。我想如何啓動腳本?只是在輸入文件不工作後才加入 – user2710445

+0

@ user2710445:我將文件名硬編碼爲'file1'和'file2'。如果你想讓它們作爲腳本的參數,只需用'shift'替換它們。正如在'打開我的$ F1'中,'<',移動或死掉$!'。 – choroba