Bash: resolving awk run time error, negative field index

If you are using awk with a relatively indexed NF variable (number of fields), and get an error like below, this is because the input being parsed does not have the number of fields expected.

awk: run time error: negative field index $-1

The root problem is the awk expression was expecting a certain number of fields and perhaps there is an empty line, a free-form comment line, or other unexpected format that means the field count is low and therefore the indexing is not possible.

Example of successful and failed awk expression

Consider the successful example below where we use awk to split the input by a forward slash “/”, and get the last two directories in a path using NF-2 and NF-1

$ line="/a/b/c/file1-abc.txt"
$ echo "$line" | awk -F/ '{printf "last 2 dir paths = %s/%s\n",$(NF-2),$(NF-1) }'
last 2 dir paths = b/c

If we were parsing multiple lines of standard input with awk and the line happened to be empty, or contain a free-form comment like below, we would get the index error.

$ line="# comment line"
$ echo "$line" | awk -F/ '{printf "last 2 dir paths = %s/%s\n",$(NF-2),$(NF-1) }'
awk: cmd. line:1: (FILENAME=- FNR=1) fatal: attempt to access field -1

Resolution

This error can be avoided by adding a conditional to the NF expression which first checks whether the field  index exists.

$ echo "$line" | awk -F/ '{printf "last 2 dir paths = %s/%s\n",(NF>2 ? $(NF-2):"None"),(NF>1 ? $(NF-1):"None") }'
last 2 dir paths = None/None

REFERENCES

stackoverflow, bash extracting last two dirs for a pathname

stackoverflow, awk run time error negative field index

awk man page