adding numbers from n subsequent lines with bash or awk -


i have file:

foobar 4 barfoo 3 forabo 2 afoorb 5 

and want add numbers in second row n lines. if n=2 result like

barfoo 7 forabo 5 afoorb 7 

how do that?

for general solution works n, save values in array using line number index, , delete values after using. sort of queue.

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

after clarification, seems want sum of values, example n=3, expected output:

forabo 9 afoorb 10 

in case:

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

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -