Skip to content
Advertisement

How to insert a new record(row or line) after the last line of input file using awk?

The marks of the students are given as a table in the following format Name | rollno | marks in exam1 | marks in exam 2 … i.e. There is one record per line and each column is separated by a | (pipe) character.At the end of all the records I want to add extra lines which contains information about max, min mean…So my question is How would one add new record at the end of input file?

Example: Here is a sample input

Piyush | 12345 |     5 |     5 |     4

James  |   007 |     0 |     0 |     7

Knuth  | 31415 |   100 |   100 |   100

For which the output is

Piyush | 12345 |     5 |     5 |     4 |     14

James  |   007 |     0 |     0 |     7 |      7

Knuth  | 31415 |   100 |   100 |   100 |    300

max    |       |   100 |   100 |   100 |    300

min    |       |     0 |     0 |     4 |      7

mean   |       | 35.00 | 35.00 | 37.00 | 107.00

sd     |       | 46.01 | 46.01 | 44.56 | 136.50 

Advertisement

Answer

awk '
BEGIN { FS=OFS="|" }
{
    sum = 0
    for (i=3;i<=NF;i++) {
        tot[i] += $i
        sum += $i
        max[i] = ( (i in max) && (max[i] > $i) ? max[i] : $i )
    }
    print $0, sum
    max[i] = ( (i in max) && (max[i] > sum) ? max[i] : sum )
}
END {
    printf "max" OFS ""
    nf = NF+1
    for (i=3; i<=nf; i++) {
        printf "%s%s", max[i], (i<nf?OFS:ORS)
    }
}'

repeat for min and whatever else you need to calculate and check the printf formatting flags for whatever spacing you need, if any.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement