Bash and Linux

Total the bytes served in an access log

easyawk and cut

Problem statement

Finance wants to know how much traffic a web server served. In the common log format below, field 10 is the response size in bytes, and it is - when no body was sent. Print the total number of bytes served.

access.log

TEXT
10.0.0.5 - - [20/Sep/2026:10:00:01 +0000] "GET /index.html HTTP/1.1" 200 5120
10.0.0.7 - - [20/Sep/2026:10:00:02 +0000] "GET /api/users HTTP/1.1" 200 842
10.0.0.5 - - [20/Sep/2026:10:00:04 +0000] "POST /api/login HTTP/1.1" 401 120
10.0.0.9 - - [20/Sep/2026:10:00:05 +0000] "GET /static/app.js HTTP/1.1" 200 20480
10.0.0.7 - - [20/Sep/2026:10:00:07 +0000] "HEAD /index.html HTTP/1.1" 304 -
10.0.0.5 - - [20/Sep/2026:10:00:09 +0000] "GET /api/users HTTP/1.1" 500 64

Examples

Example 1

Input: Run the command on `access.log`.

Output: 26626

Explanation: 5120 + 842 + 120 + 20480 + 0 + 64. The - counts as 0.

Hints

Approach

Optimal

awk splits each line on whitespace, so field 10 is the size. sum += $10 runs for every line and adds that field to a running total; awk variables start as 0, so no initialisation is needed. The END block runs once after all input is read and prints the total. When awk converts - to a number it becomes 0, so the 304 response adds nothing, which is the correct meaning.

Bash
awk '{ sum += $10 } END { print sum }' access.log

Follow-up questions

  • Print the total in megabytes with two decimals.
  • Print the total bytes per status code instead of one grand total.

Frequently asked questions

awk stores numbers as floating point and print uses the OFMT format (%.6g) for non-integers and very large values. Use printf "%d\n", sum or printf "%.0f\n", sum to force a plain integer.