Shravan Kumar Shravan Kumar - 23 days ago 11
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.
Required:

$ cat sample.csv
1,1,1,30,40,23,24,25,26,27,28,29,0,0,0,0,0,0,0,0
1,2,1,35,40,33,34,35,36,37,38,39,12,13,14,15,16,17,22,36
1,3,1,45,50,43,44,45,46,47,48,49,22,23,24,25,26,27,33,38


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.

Answer

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

Output

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

Explanation

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
Comments