Shravan Kumar Shravan Kumar - 4 months ago 26
Bash Question

using awk to process next column values with current line value

I am new to awk, couldn't figure out how to process next record columns, any help would be appreciated.

$ cat sample.csv

I am able to get half of my required, in line 1, i am not able to process Line 2 values

$ cat sample.csv | awk -F"," '{a+=$4}{b+=$5}{c+=$6}{d+=$7}{e+=$8}{f+=$9}{g+=$10}{h+=$11}{i+=$12}{j+=$13}{k+=$14}{l+=$15}{m+=$16}{n+=$17}{o+=$18}{p+=$19}END{print "Line 1 " a+b-c-d-e-f-g-h}'

Line 1 -399

I am looking for the expression
a+b-c-d-e-f-g-h - (NextRecord i+j+k+l+m+n)

For the last record, we can consider the next record values as 0's.


Try this awk command:

awk -F, 'NR!=1{print "Line", NR-1, (l-$12-$13-$14-$15-$16-$17)} {l=($4+$5-$6-$7-$8-$9-$10-$11)}  END {print "Line", NR, l} ' /tmp/sample.csv


Line 1 -192
Line 2 -307
Line 3 -178


awk -F, '
 NR != 1 {                        # Skip first record
   print "Line", NR-1, \          # Print the output using the data from 
     (l-$12-$13-$14-$15-$16-$17)  # the last record
 {l=($4+$5-$6-$7-$8-$9-$10-$11)}  # Store this for later
 END {print "Line", NR, l}        # Specific case for last record
' /tmp/sample.csv                 # filename