Skip to content

/errors/awk/fatal-division-by-zero-attempted

awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · GNU Awk 5.4.1updated
tool
awk
exit code
2
versions
GNU Awk 4.x – 5.x
os
linux, macos, windows

awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted means a / or % in your awk program had 0 on the right side, and gawk treats that as a fatal error: it stops at that line and exits with status 2. In awk an empty or non-numeric field counts as 0, so the usual cause is a blank field, a header line or a wrong field separator. Guard the division with a numeric test such as $2 + 0 != 0. FILENAME and FNR in the message tell you the file (- is standard input) and the line number.

Reproduce the error

bash
printf '10 2\n7 0\n' | awk '{ print $1 / $2 }'

Output · exit 2

5
awk: cmd. line:1: (FILENAME=- FNR=2) fatal: division by zero attempted

The first line printed 5 before the fatal error on line 2. A header line has the same effect, because the text count is 0 as a number:

bash
printf 'total count\n10 2\n' | awk '{ print $1 / $2 }'

Output · exit 2

awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted

Fix: guard the divisor

bash
printf 'total count\n10 2\n7 0\n9\n' | awk 'NR > 1 { print ($2 + 0 != 0 ? $1 / $2 : "n/a") }'

Output

5
n/a
n/a

NR > 1 skips the header; the ternary prints n/a for both a 0 and a missing field. The + 0 matters: a missing field is an empty string, and $2 != 0 compares it with 0 as a string, which is true, so the division still runs:

bash
printf '9\n' | awk '{ print ($2 != 0 ? $1 / $2 : "n/a") }'

Output · exit 2

awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted

Averages in END

When no line matches, the counter is still 0 in END:

bash
printf 'a 1\nb 2\n' | awk '/^z/ { sum += $2; n++ } END { print sum / n }'

Output · exit 2

awk: cmd. line:1: (FILENAME=- FNR=2) fatal: division by zero attempted
bash
printf 'a 1\nb 2\n' | awk '/^z/ { sum += $2; n++ } END { if (n) print sum / n; else print "no rows" }'

Output

no rows

Sources