kernash
kernash

Reputation: 25

adding numbers from n subsequent lines with bash or awk

I have a file:

foobar 4
barfoo 3
forabo 2
afoorb 5

and i want to add the numbers in the second row from n lines. If n=2 the result would look like

barfoo 7
forabo 5
afoorb 7

How do i do that?

Upvotes: 1

Views: 54

Answers (2)

Indrajit
Indrajit

Reputation: 2152

Here is a my version - may not be the best, but I had fun trying to solve this one:

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

Upvotes: 0

janos
janos

Reputation: 124648

For a general solution that works with any n, you could save values in an array using the line number as index, and delete values after using. Sort of like a queue.

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

After some clarification, it seems you want the sum of values, for example for n=3, the expected output:

forabo 9
afoorb 10

In that case:

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 }
'

Upvotes: 1

Related Questions