Linux Labs

Bash: text processing and scripts / Stage 2 of 9

sed and awk: editing and fields of a stream

Not running Starting usually ~20 s
Leave the lesson

Step 4 of 9 · on a machine · 5 min

Columns and a sum

The accountant asks for the total of October's payments from payments.csv. cut will cut out the column, but it cannot add numbers.

awk runs a short program for every line. It splits the line into fields: the first is $1, the second $2 and so on. The program { s += $3 } adds the third field to the variable s, and the END { print s } block runs once, after the last line, and prints the total. Look at the file and add up the amount column.

Exercise · look

Add up the amount column

In ~/sed-lab, look at the start of payments.csv and add up the amount column — first without the -F option, then with it.

First, predict

What will the first awk command, without -F, print?

Now start the exercise, run the command and compare your prediction with the output.

Sign in and start The machine is available after signing in

By default awk splits a line on spaces and tabs. A CSV line has no spaces, so to awk the whole line is one field, $1; there is no third field, and the sum stayed at zero. The -F',' option sets the separator to a comma, and $3 becomes the amount column. The last field, however many there are, is $NF. awk added the header line too: it counts the word amount as zero.

Ubuntu 24.04
Loading…