How to count values between empty cells

With tac and any awk:

tac file | awk 'NF==2{sum+=$2; print; next} {print $1 "\t" sum; sum=0}' | tac

With two improvements proposed by kvantour and Ed Morton. See the comments.

tac file | awk '($NF+0==$NF){sum+=$2; print; next} {print $1 "\t" sum+0; sum=0}' | tac

See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR


Could you please try following, written and tested with shown samples in GNU awk.

awk '
FNR==NR{
  if($0!~/line/){  a[$0]; prev=$0 }
  else          {  a[prev]+=$NF   }
  next
}
!/line/{
  $0=$0 OFS (a[$0]?a[$0]:0)
}
1'  Input_file  Input_file

OR in case you want output in good looking form add column -t to above command like as follows:

awk '
FNR==NR{
  if($0!~/line/){  a[$0]; prev=$0 }
  else          {  a[prev]+=$NF   }
  next
}
!/line/{
  $0=$0 OFS (a[$0]?a[$0]:0)
}
1'  Input_file  Input_file  |  column -t

Explanation: Adding detailed explanation for above code.

awk '                                           ##Starting awk program from here.
FNR==NR{                                        ##Checking FNR==NR which will be TRUE when Input_file is being read first time.
  if($0!~/line/){  a[$0]; prev=$0 }             ##checking condition if line contains string line and setting index of current line in a and setting prev value to current line.
  else          { a[prev]+=$NF    }             ##Else if line not starting from line then creating array a with index prev variable and keep on adding last field value to same index of array.
  next                                          ##next will skip all further statements from here.
}
!/line/{                                        ##Checking if current line doesnot have line keyword in it then do following.
  $0=$0 OFS (a[$0]?a[$0]:0)                     ##Re-creating current line with its current value then OFS(which is space by default) then either add value of a[$0] or 0 based on current line value is NOT NULL here.
}
1                                               ##Printing current line here.
' Input_file  Input_file                        ##Mentioning Input_file names here.

In plain awk:

awk '{
    if (NF == 1) {
        if (blockname)
            printf("%s\t%.2f\n%s", blockname, sum, lines)
        blockname = $0
        sum = 0
        lines=""
    } else if (NF == 2) {
        sum += $2 
        lines = lines $0 "\n"
    }
    next
}
END { printf("%s\t%.2f\n%s", blockname, sum, lines) }
' input.txt

Tags:

Awk