2016-05-28 28 views
1

添加數字我有一個文件:從n個後續行bash或AWK

foobar 4 
barfoo 3 
forabo 2 
afoorb 5 

,我想從n行的第二行中添加的號碼。 如果n = 2的結果會是什麼樣子

barfoo 7 
forabo 5 
afoorb 7 

我該怎麼做呢?

回答

1

對於可與任何n, 一起使用的一般解決方案,您可以使用行號作爲索引 將值保存到數組中,並在使用後刪除值。 有點像排隊。

awk -v n=2 ' 
    NR >= n { 
    print $1, ($2 + q[NR - n + 1]); 
    delete q[NR - n + 1]; 
    } 
    { q[NR] = $2 } 
' 

一些澄清後,似乎你想要的值 例如用於n=3總和,預期輸出:

forabo 9 
afoorb 10 

在這種情況下:

awk -v n=2 ' 
    NR >= n { 
    idx = NR - n + 1; 
    sum = 0; 
    for (i = 0; i < n - 1; i++) sum += q[idx + i]; 
    print $1, $2 + sum; 
    delete q[idx]; 
    } 
    { q[NR] = $2 } 
' 
+0

@kernash我修改了我的答案,讓我知道它是否仍然不是你想要的,並解釋了8來自「forabo 8」 – janos

0

這裏我的版本 - 可能不是最好的,但我很樂意試圖解決這個問題:

echo Here goes nothing 
rowCnt=2 
declare -i numOfLines 
declare -i x2 
declare -i tot 
declare -i y2 
declare -i j 
numOfLines=$(wc -l < lines.txt) 
for ((c=1; c<=$numOfLines; c++)) 
do 
    line=`sed -n ${c}p lines.txt` 
    read -r x1 x2 <<< "$line" 
    if (($c >= $rowCnt)) 
    then 
     tot=0 
     for ((j=$c-$rowCnt+1; j<=$c; j++)) 
     do 
      seek=`sed -n ${j}p lines.txt` 
      read -r y1 y2 <<< "$seek" 
      tot=$tot+$y2 
     done 
     echo "$x1" "$tot" 
    fi 
done